-
Notifications
You must be signed in to change notification settings - Fork 4
/
index.js
89 lines (78 loc) · 2.08 KB
/
index.js
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
import { getplaceCache, purgeCache } from "./lib/cache";
import jsonResponse from "./lib/jsonResponse";
import place from "./src/place";
import search from "./src/search";
import searchAndGo from "./src/seratch-and-go";
addEventListener("fetch", (event) => {
event.respondWith(handleRequest(event.request));
});
async function handleRequest(request) {
const path = new URL(request.url).pathname;
if (request.method == "OPTIONS") {
// Handel Preflight Requests
return jsonResponse({
data: {
message: "Preflight request successful!",
},
});
}
switch (path) {
case "/":
return jsonResponse({
data: {
message: "Working!",
search: "/search?query={query}",
place: "/place/{id}",
madeBy: "tuhinpal <[email protected]>",
github: "https://github.com/tuhinpal/thingstodo",
},
});
case "/search":
return search({
query: new URL(request.url).searchParams.get("query"),
});
case `/search-and-go/${path.split("/")[2]}`:
var searchCache = await getplaceCache(`search-${path.split("/")[2]}`);
if (searchCache) {
return jsonResponse({
data: searchCache,
headers: {
cache: "HIT",
},
});
} else {
return searchAndGo({
query: path.split("/")[2],
});
}
case `/place/${path.split("/")[2]}`:
var getcache = await getplaceCache(path.split("/")[2]);
if (getcache) {
return jsonResponse({
data: getcache,
headers: {
cache: "HIT",
},
});
} else {
return place({
id: path.split("/")[2],
});
}
case `/purge/${SECRET}`: // set SECRET in environment variables at cf dashboard
var deleted = await purgeCache();
return jsonResponse({
data: {
message: "Cache purged!",
deleted,
},
});
default:
return jsonResponse({
data: {
message: "Not found!",
},
status: 404,
});
}
}