-
Notifications
You must be signed in to change notification settings - Fork 2
/
worker.ts
92 lines (82 loc) · 2.23 KB
/
worker.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
import { createRequestHandler } from "@remix-run/cloudflare";
import { type AppLoadContext } from "@remix-run/server-runtime";
import {
getAssetFromKV,
NotFoundError,
MethodNotAllowedError,
type CacheControl,
} from "@cloudflare/kv-asset-handler";
import manifestJSON from "__STATIC_CONTENT_MANIFEST";
import { RemixAuthService } from "./services/auth";
import { D1ItemsService } from "./services/items.d1";
import { MockItemsService } from "./services/items.mock";
import * as build from "./build/index.js";
const assetManifest = JSON.parse(manifestJSON);
const remixHandler = createRequestHandler(build, process.env.NODE_ENV);
export default {
async fetch(
request: Request,
env: Env,
ctx: ExecutionContext
): Promise<Response> {
try {
return await getAssetFromKV(
{
request,
waitUntil(promise) {
return ctx.waitUntil(promise);
},
},
{
cacheControl,
ASSET_NAMESPACE: env.__STATIC_CONTENT,
ASSET_MANIFEST: assetManifest,
}
);
} catch (e) {
if (e instanceof NotFoundError || e instanceof MethodNotAllowedError) {
// fall through to the remix handler
} else {
return new Response("An unexpected error occurred", { status: 500 });
}
}
if (!env.SESSION_SECRET) {
console.error("Please define the SESSION_SECRET environment variable");
return new Response("Internal Server Error", { status: 500 });
}
const loadContext: AppLoadContext = {
services: {
auth: new RemixAuthService([env.SESSION_SECRET!]),
// items: new MockItemsService(),
items: new D1ItemsService(env.APP_DB),
},
};
try {
return await remixHandler(request, loadContext);
} catch (reason) {
console.error(reason);
return new Response("Internal Server Error", { status: 500 });
}
},
};
function cacheControl(request: Request): Partial<CacheControl> {
const url = new URL(request.url);
if (url.pathname === "/sw.js") {
return {
browserTTL: 0,
edgeTTL: 0,
};
}
if (url.pathname.startsWith("/build")) {
// Cache build files for 1 year since they have a hash in their URL
return {
browserTTL: 60 * 60 * 24 * 365,
edgeTTL: 60 * 60 * 24 * 365,
};
}
// Cache everything else for 10 minutes
return {
browserTTL: 60 * 10,
edgeTTL: 60 * 10,
};
}