generated from kawarimidoll/deno-dev-template
-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.ts
42 lines (33 loc) · 1.05 KB
/
server.ts
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
/// <reference path="./_deploy.d.ts" />
import { zennApi } from "./zenn_api.ts";
const port = 8080;
const listener = Deno.listen({ port });
const isProd = !!Deno.env.get("DENO_DEPLOYMENT_ID");
if (!isProd) {
console.log(`HTTP server listening on http://localhost:${port}`);
}
// cache one hour
const CACHE_MAX_AGE = 3600;
async function handleConn(conn: Deno.Conn) {
const httpConn = Deno.serveHttp(conn);
for await (const e of httpConn) {
e.respondWith(handler(e.request));
}
}
async function handler(request: Request) {
const { pathname, searchParams } = new URL(request.url);
console.log({ pathname, searchParams });
const result = await zennApi(pathname, searchParams);
const status = Object.hasOwn(result, "error") ? 400 : 200;
const body = JSON.stringify(result);
const headers = new Headers({
"Content-Type": "application/json",
});
if (isProd) {
headers.set("Cache-Control", `public, max-age=${CACHE_MAX_AGE}`);
}
return new Response(body, { status, headers });
}
for await (const conn of listener) {
handleConn(conn);
}