-
Notifications
You must be signed in to change notification settings - Fork 0
/
api.js
216 lines (191 loc) · 8.36 KB
/
api.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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
const NS = SUB;
const apiMethods = ["GET", "POST", "PUT", "DELETE", "OPTIONS"];
const apiVersion = ["v1", "v2"];
const apiService = ["db", "search", "move"];
const DEFAULT_SECURITY_HEADERS = {
/*
Secure your application with Content-Security-Policy headers.
Enabling these headers will permit content from a trusted domain and all its subdomains.
@see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy
"Content-Security-Policy": "default-src 'self' example.com *.example.com",
*/
/*
You can also set Strict-Transport-Security headers.
These are not automatically set because your website might get added to Chrome's HSTS preload list.
Here's the code if you want to apply it:
"Strict-Transport-Security" : "max-age=63072000; includeSubDomains; preload",
*/
/*
Permissions-Policy header provides the ability to allow or deny the use of browser features, such as opting out of FLoC - which you can use below:
"Permissions-Policy": "interest-cohort=()",
*/
/*
X-XSS-Protection header prevents a page from loading if an XSS attack is detected.
@see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-XSS-Protection
*/
"X-XSS-Protection": "0; mode=block",
/*
X-Frame-Options header prevents click-jacking attacks.
@see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Frame-Options
*/
"X-Frame-Options": "DENY",
/*
X-Content-Type-Options header prevents MIME-sniffing.
@see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Content-Type-Options
*/
"X-Content-Type-Options": "nosniff",
"Referrer-Policy": "strict-origin-when-cross-origin",
"Cross-Origin-Embedder-Policy": 'require-corp; report-to="default";',
"Cross-Origin-Opener-Policy": 'same-site; report-to="default";',
"Cross-Origin-Resource-Policy": "same-site",
};
const JSON_HEADERS = {
"Content-Type": "application/json; charset=utf-8",
};
const OPTIONS_HEADERS = {
"Access-Control-Allow-Methods": "GET,POST,PUT,DELETE,OPTIONS",
};
Object.assign(JSON_HEADERS, DEFAULT_SECURITY_HEADERS);
Object.assign(OPTIONS_HEADERS, DEFAULT_SECURITY_HEADERS);
addEventListener("fetch", (event) =>
event.respondWith(handleRequest(event.request))
);
function JsonBody(value, key) {
const obj = {};
if (key) {
obj[key] = value;
} else {
obj["msg"] = value;
}
return JSON.stringify(obj, null, 2);
}
const initHeader = (code) => {
return { status: code, headers: JSON_HEADERS };
};
async function handleRequest(request) {
const method = request.method;
if (apiMethods.indexOf(method) !== -1) {
if (method === "OPTIONS") {
return new Response(null, { status: 204, headers: OPTIONS_HEADERS });
}
// path will be: /v1/db/:key
const url = new URL(request.url)
const { pathname } = url
const args = pathname.split("/");
const ver = args[1];
if (apiVersion.indexOf(ver) !== -1) {
const service = args[2];
if (apiService.indexOf(service) !== -1) {
const key = args[3];
const postBody = request.body
switch (service) {
case "db":
if (key) {
const dbErrMsg = `msg: POST/PUT object example {"value": "https://example.com"}`
const value = await NS.get(key)
switch (method) {
case "GET":
if (value) return new Response(JsonBody(value, key), initHeader(200))
return new Response(JsonBody(`Value of ${key} not found`), initHeader(404))
case "POST":
if (value) return new Response(JsonBody(`${key} already exists`), initHeader(409))
let postObj
try {
postObj = await request.json()
} catch (e) {
return new Response(dbErrMsg, initHeader(400))
}
if (postBody) {
if (postObj) {
const postVal = postObj["value"];
if (postVal) {
await NS.put(key, postVal)
return new Response(JsonBody(postVal, key), initHeader(201))
}
return new Response(JsonBody("value in POST object not found"), initHeader(404))
}
}
return new Response(dbErrMsg, initHeader(400))
case "PUT":
if (!value) return new Response(JsonBody(`${key} not exists, please create it`), initHeader(404))
let putObj
try {
putObj = await request.json()
} catch (e) {
return new Response(dbErrMsg, initHeader(400))
}
if (postBody) {
if (putObj) {
const putVal = putObj["value"];
if (putVal) {
await NS.put(key, putVal)
return new Response(JsonBody(putVal, key), initHeader(201))
}
}
}
return new Response(dbErrMsg, initHeader(400))
case "DELETE":
if (!value) return new Response(JsonBody(`${key} not exists, delete noting`), initHeader(404))
await NS.delete(key)
return new Response(JsonBody(`${key} already deleted`), initHeader(200))
default:
return new Response(JsonBody(`Method ${method} not allowed.`), { status: 405, headers: { Allow: "GET,POST,PUT,DELETE" } });
}
}
return new Response(JsonBody("Key not valid"), initHeader(403));
case "search":
if (method !== "GET") return new Response(JsonBody(`Method ${method} not allowed.`), { status: 405, headers: { Allow: "GET" } });
if (key) {
const list = await NS.list({ prefix: key })
const listKeys = list.keys
if (listKeys) return new Response(JSON.stringify(listKeys, null, 2), { status: 200 });
return new Response(JsonBody("List is empty"), { status: 404 });
}
return new Response(JsonBody("Key not valid"), initHeader(403));
case "move":
console.log(`move: ${key}`)
// Github Copilot, I love you
if (method !== "PUT") return new Response(JsonBody(`Method ${method} not allowed.`), { status: 405, headers: { Allow: "PUT" } });
if (key) {
if (postBody) {
const moveErrMsg = `msg: PUT object example {"newKey": "bpple", "value": "if you want change value at once, add me"}`
let moveObj
try {
moveObj = await request.json()
} catch (e) {
return new Response(moveErrMsg, initHeader(400))
}
if (moveObj) {
const newKey = moveObj["newKey"];
if (newKey) {
const newValue = moveObj["value"];
if (newValue) {
await NS.delete(key)
await NS.put(newKey, newValue)
return new Response(JsonBody(newValue, newKey), initHeader(201))
}
const value = await NS.get(key)
if (value) {
await NS.delete(key)
await NS.put(newKey, value)
return new Response(JsonBody(value, newKey), initHeader(201))
}
return new Response(JsonBody(`${key} not exists, can't move it`), initHeader(404))
}
return new Response(JsonBody("newKey in move object not found"), initHeader(404))
}
return new Response(JsonBody("move object not found"), initHeader(404))
}
return new Response(moveErrMsg, initHeader(400))
}
return new Response(JsonBody("Key not valid"), initHeader(403));
default:
return new Response(JsonBody("Service mismatched"), initHeader(500));
}
}
return new Response(JsonBody("Service mismatched"), initHeader(500));
}
return new Response(JsonBody("API version mismatched"), initHeader(500));
}
return new Response(JsonBody(`Method ${method} not allowed.`), { status: 405, headers: OPTIONS_HEADERS });
}