-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.ts
More file actions
74 lines (72 loc) · 2.21 KB
/
Copy pathserver.ts
File metadata and controls
74 lines (72 loc) · 2.21 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
68
69
70
71
72
73
74
import { join } from "@std/path/join";
import { Code, getCode, putCode } from "./code.ts";
import {
type Handler,
logTime,
methods,
parseBodyAsJson,
route,
STATUS_CODE,
supportedMethods,
} from "./handler.ts";
import { decodeURLPathComponents, staticFile } from "./static.ts";
export function getHandler(kv: Deno.Kv): Handler {
return logTime(supportedMethods(
["GET", "POST"],
route(
{
"/api/*": route({
"/code": methods({
POST: parseBodyAsJson(Code, async (_, { body: code }) => {
const id = await putCode(kv, code);
return Response.json({ id }, { status: STATUS_CODE.Created });
}),
}),
"/code/:id": methods({
GET: async (_, { params: { id } }) => {
const code = await getCode(kv, id!);
if (!code) {
return Response.json(
{ error: "Code not found" },
{ status: STATUS_CODE.NotFound },
);
}
return Response.json({ code });
},
}),
}, () =>
Response.json(
{ error: "Not found" },
{ status: STATUS_CODE.NotFound },
)),
},
methods({
GET: route({
"/": () => staticFile("index.html"),
"/c/:id": () => staticFile("index.html"),
"/sw.js": () => staticFile("sw.js"),
"/sw.js.map": () => staticFile("sw.js.map"),
"/robots.txt": () => staticFile("robots.txt"),
}, async (req) => {
const path = decodeURLPathComponents(new URL(req.url).pathname);
if (path) {
try {
return await staticFile(join("dist", ...path), {
cacheControl: "max-age=2592000, immutable",
});
} catch (e) {
if (
!(e instanceof Deno.errors.NotFound ||
e instanceof Deno.errors.NotADirectory ||
e instanceof Deno.errors.IsADirectory)
) {
throw e;
}
}
}
return await staticFile("404.html", { status: STATUS_CODE.NotFound });
}),
}),
),
));
}