initial import: random background api
This commit is contained in:
36
functions/api/random.js
Normal file
36
functions/api/random.js
Normal file
@@ -0,0 +1,36 @@
|
||||
import { buildAssetUrl, detectVariant, getVariantPayload, loadManifest, pickRandom } from '../lib/background.js';
|
||||
|
||||
export async function onRequestGet(context) {
|
||||
const { request } = context;
|
||||
const url = new URL(request.url);
|
||||
const format = (url.searchParams.get('format') || 'redirect').toLowerCase();
|
||||
const manifest = await loadManifest(request);
|
||||
const variant = detectVariant(request);
|
||||
const { folder, images } = getVariantPayload(manifest, variant);
|
||||
|
||||
if (!images.length) {
|
||||
return Response.json(
|
||||
{ error: 'no images available', variant, folder },
|
||||
{ status: 404, headers: { 'Cache-Control': 'no-store, max-age=0', 'Access-Control-Allow-Origin': '*' } },
|
||||
);
|
||||
}
|
||||
|
||||
const filename = pickRandom(images);
|
||||
const assetUrl = buildAssetUrl(request, folder, filename);
|
||||
|
||||
if (format === 'json') {
|
||||
return Response.json(
|
||||
{ variant, folder, filename, url: assetUrl, count: images.length },
|
||||
{ headers: { 'Cache-Control': 'no-store, max-age=0', 'Access-Control-Allow-Origin': '*' } },
|
||||
);
|
||||
}
|
||||
|
||||
return new Response(null, {
|
||||
status: 302,
|
||||
headers: {
|
||||
Location: assetUrl,
|
||||
'Cache-Control': 'no-store, max-age=0',
|
||||
'Access-Control-Allow-Origin': '*',
|
||||
},
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user