Script Worker Player
export default {
async fetch(request, env, ctx) {
const cache = caches.default;
const url = new URL(request.url);
const pathname = url.pathname;
// === DOMAIN YANG DIIJINKAN ===
const allowedOrigins = ['https://heylinktasriadibola2.blogspot.com'];
const origin = request.headers.get('Origin');
const safeOrigin = origin && allowedOrigins.includes(origin)
? origin
: 'https://heylinktasriadibola2.blogspot.com';
if (origin && !allowedOrigins.includes(origin)) {
return new Response('Forbidden: Access not allowed', { status: 403 });
}
// === PETA LINK DATA ===
const sources = {
// data besar → dari Google Drive (file JSON statis)
'/data': 'https://drive.google.com/uc?export=view&id=1iu8Sh5V3AnGF1IEmjJ0gAkqfOtFKWrgS',
// data kecil → langsung dari Apps Script (karena ringan)
'/backup': 'https://script.google.com/macros/s/AKfycbxrwoJeBX9lw-jXu0CFDFCnX9Ietox29cVqLbUkvFji4WJSIbgMsO2H2Z7HvPX3i7xcYA/exec',
};
const dataURL = sources[pathname];
if (!dataURL) return new Response('Not Found', { status: 404 });
const cacheKey = new Request(request.url);
let cachedResponse = await cache.match(cacheKey);
// === JIKA CACHE ADA ===
if (cachedResponse) {
const headers = new Headers(cachedResponse.headers);
headers.set('Access-Control-Allow-Origin', safeOrigin);
headers.set('Vary', 'Origin');
headers.set('X-Cache-Status', 'HIT');
// Update cache di background
//ctx.waitUntil(updateCache(dataURL, cacheKey, cache));
return new Response(cachedResponse.body, {
status: cachedResponse.status,
headers
});
}
// === CACHE TIDAK ADA, FETCH DULU ===
return await fetchAndCache(dataURL, cacheKey, cache, safeOrigin, ctx);
},
};
// === Fungsi untuk fetch dan simpan ke cache ===
async function fetchAndCache(dataURL, cacheKey, cache, safeOrigin, ctx) {
try {
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), 15000); // timeout 15 detik
const response = await fetch(dataURL, { signal: controller.signal });
clearTimeout(timeout);
if (!response.ok) throw new Error(`Fetch error: ${response.status}`);
const data = await response.text();
const res = new Response(data, {
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': safeOrigin,
'Vary': 'Origin',
'Cache-Control': 'public, max-age=300, stale-while-revalidate=300',
'X-Cache-Status': 'MISS',
},
});
// Simpan hasil ke cache selama 10 menit
ctx.waitUntil(
cache.put(
cacheKey,
new Response(data, {
headers: {
'Content-Type': 'application/json',
'Cache-Control': 'public, max-age=300, stale-while-revalidate=300',
},
})
)
);
return res;
} catch (err) {
return new Response(
JSON.stringify({ error: true, message: 'Gagal memuat data: ' + err.message }),
{
status: 500,
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': safeOrigin,
},
}
);
}
}
// === Fungsi untuk memperbarui cache di background ===
async function updateCache(dataURL, cacheKey, cache) {
try {
const res = await fetch(dataURL);
if (!res.ok) throw new Error(`Failed to refresh cache: ${res.status}`);
const data = await res.text();
await cache.put(
cacheKey,
new Response(data, {
headers: {
'Content-Type': 'application/json',
'Cache-Control': 'public, max-age=300, stale-while-revalidate=300',
},
})
);
console.log('Cache updated successfully:', cacheKey.url);
} catch (err) {
console.warn('Cache update failed:', err.message);
}
}
Posting Komentar