-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathworker.js
More file actions
67 lines (56 loc) · 1.88 KB
/
Copy pathworker.js
File metadata and controls
67 lines (56 loc) · 1.88 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
// Architect as a Service (AaaS) — Cloudflare Worker
// True random GET API. Single source of truth: responses.json (bilingual pl/en)
import data from "./responses.json";
const CORS = {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET, OPTIONS",
"Content-Type": "application/json; charset=utf-8",
};
const LANGS = ["pl", "en"];
function pick(list) {
return list[Math.floor(Math.random() * list.length)];
}
// Resolve language from /pl, /en path prefix or ?lang= ; default pl
function resolveLang(url) {
const seg = url.pathname.split("/").filter(Boolean)[0];
if (LANGS.includes(seg)) return seg;
const q = url.searchParams.get("lang");
if (LANGS.includes(q)) return q;
return "pl";
}
export default {
async fetch(request) {
const url = new URL(request.url);
if (request.method === "OPTIONS") {
return new Response(null, { headers: CORS });
}
const lang = resolveLang(url);
const segs = url.pathname.split("/").filter(Boolean);
const sub = LANGS.includes(segs[0]) ? segs[1] : segs[0];
// /all or /<lang>/all -> full list in that language
if (sub === "all") {
const body = {
persona: data.persona,
lang,
responses: data.responses.map((r) => ({ message: r[lang], status: r.status })),
};
return new Response(JSON.stringify(body, null, 2), { headers: CORS });
}
// optional ?status= filter
const wanted = url.searchParams.get("status");
let pool = data.responses;
if (wanted) {
const filtered = pool.filter((r) => r.status === wanted);
if (filtered.length) pool = filtered;
}
const choice = pick(pool);
const body = {
persona: data.persona,
lang,
message: choice[lang],
status: choice.status,
timestamp: new Date().toISOString(),
};
return new Response(JSON.stringify(body, null, 2), { headers: CORS });
},
};