// Cloudflare Worker — сохраняет карты и отдаёт случайную
export default {
async fetch(request, env) {
const url = new URL(request.url);
// Админ загружает карты (POST /upload)
if (request.method === 'POST' && url.pathname === '/upload') {
// Проверка пароля (в реальности лучше через заголовки)
const auth = request.headers.get('Authorization');
if (auth !== 'Bearer 154365') {
return new Response('Unauthorized', { status: 401 });
}
const formData = await request.formData();
const files = formData.getAll('images');
const savedUrls = [];
for (const file of files) {
const key = `cards/${Date.now()}-${file.name}`;
await env.MY_BUCKET.put(key, file.stream(), {
httpMetadata: { contentType: file.type }
});
// Сохраняем URL карты в список (можно в D1 или KV)
savedUrls.push(`https://your-worker.workers.dev/images/${key}`);
}
// Сохраняем список всех карт в KV хранилище
const existing = await env.KV_NAMESPACE.get('cards', 'json') || [];
const allCards = [...existing, ...savedUrls];
await env.KV_NAMESPACE.put('cards', JSON.stringify(allCards));
return new Response(JSON.stringify({ success: true, count: savedUrls.length }), {
headers: { 'Content-Type': 'application/json' }
});
}
// Посетитель получает случайную карту (GET /random)
if (request.method === 'GET' && url.pathname === '/random') {
const cards = await env.KV_NAMESPACE.get('cards', 'json') || [];
if (cards.length === 0) {
return new Response(JSON.stringify({ url: null }), {
headers: { 'Content-Type': 'application/json' }
});
}
const randomCard = cards[Math.floor(Math.random() * cards.length)];
return new Response(JSON.stringify({ url: randomCard }), {
headers: { 'Content-Type': 'application/json' }
});
}
return new Response('Not found', { status: 404 });
}
}