-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathserver.ts
96 lines (89 loc) · 1.94 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
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
//
// BEGIN
//
import { Hono } from "hono";
import {
MethodNotAllowedError,
NotFoundError,
getAssetFromKV,
serveSinglePageApp,
} from "@cloudflare/kv-asset-handler";
import { SSRRender } from "src/entry-server";
import assetManifest from "__STATIC_CONTENT_MANIFEST";
import { cache } from "hono/cache";
type Bindings = {
__STATIC_CONTENT: KVNamespace;
};
const app = new Hono<{ Bindings: Bindings }>();
type Data = {
userId: number;
id: number;
title: string;
completed: boolean;
};
app
.get(
"*",
cache({
cacheName: "my-app",
cacheControl: "max-age=3600",
})
)
.get("/api/posts", async (c) => {
const url = "https://jsonplaceholder.typicode.com/posts";
const response = await fetch(url);
const result: Data[] = await response.json();
return c.json(result);
})
.get("/assets/*", async (c) => {
try {
return await getAssetFromKV(
{
request: c.req.raw,
waitUntil: async (p) => c.executionCtx.waitUntil(p),
},
{
ASSET_NAMESPACE: c.env.__STATIC_CONTENT,
ASSET_MANIFEST: assetManifest,
defaultETag: "strong",
mapRequestToAsset: serveSinglePageApp,
cacheControl: {
browserTTL: undefined,
edgeTTL: 2 * 60 * 60 * 24,
bypassCache: true,
},
}
);
} catch (e) {
if (e instanceof NotFoundError) {
throw new Error(e.message);
} else if (e instanceof MethodNotAllowedError) {
throw new Error(e.message);
} else {
throw new Error("An unexpected error occurred");
}
}
})
.get("*", async (c) => c.newResponse(await SSRRender()))
.notFound((c) =>
c.json(
{
message: "Not Found",
ok: false,
},
404
)
)
.onError((err, c) =>
c.json(
{
name: err.name,
message: err.message,
},
500
)
);
export default app;
//
// END
//