-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.ts
80 lines (73 loc) · 2.02 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
import { zValidator } from "@hono/zod-validator";
import type { AppLoadContext, RequestHandler } from "@remix-run/cloudflare";
import { Hono } from "hono";
import { poweredBy } from "hono/powered-by";
import { staticAssets } from "remix-hono/cloudflare";
import { remix } from "remix-hono/handler";
import { z } from "zod";
import { incrCount } from "~/lib/redis";
import type { Env } from "~/type/env";
const app = new Hono<{ Bindings: Env }>();
let handler: RequestHandler | undefined;
// @ts-ignore - cloudflare binding type
app.use(poweredBy());
const routes = app
.get(
"/hono",
zValidator("query", z.object({ queryToken: z.string() })),
async (c) => {
return c.json({ MyDemoVar: c.env.MY_DEMO_VAR });
},
)
.post("/count", zValidator("query", z.object({})), async (c) => {
try {
const count = await incrCount(c.env);
return c.json({ count });
} catch {
console.error("Redis error");
return c.json({ count: -1 });
}
});
app.use(
async (c, next) => {
if (process.env.NODE_ENV !== "development" || import.meta.env.PROD) {
// @ts-ignore - cloudflare binding type
return staticAssets()(c, next);
}
await next();
},
async (c, next) => {
if (process.env.NODE_ENV !== "development" || import.meta.env.PROD) {
const serverBuild = await import("./build/server");
return remix({
// @ts-ignore
build: serverBuild,
mode: "production",
// @ts-ignore
getLoadContext(c) {
return {
cloudflare: {
env: c.env,
},
};
},
// @ts-ignore - cloudflare binding type
})(c, next);
} else {
if (!handler) {
// @ts-expect-error it's not typed
const build = await import("virtual:remix/server-build");
const { createRequestHandler } = await import("@remix-run/cloudflare");
handler = createRequestHandler(build, "development");
}
const remixContext = {
cloudflare: {
env: c.env,
},
} as unknown as AppLoadContext;
return handler(c.req.raw, remixContext);
}
},
);
export type AppType = typeof routes;
export default app;