-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.ts
86 lines (67 loc) · 2.29 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
import express from "express";
import * as trpcExpress from "@trpc/server/adapters/express";
import { getPayloadClient } from "./get-payload";
import { nextApp, nextHandler } from "./next-utils";
import { appRouter } from "./trpc";
import { inferAsyncReturnType } from "@trpc/server";
import bodyParser from "body-parser";
import { IncomingMessage } from "http";
import nextBuild from "next/dist/build";
import { stripeWebhookHandler } from "./webhooks";
import path from "path";
import { PayloadRequest } from "payload/types";
import { parse } from "url";
const app = express();
const PORT = Number(process.env.PORT) || 3000;
const createContext = ({ req, res }: trpcExpress.CreateExpressContextOptions) => ({ req, res });
export type ExpressContext = inferAsyncReturnType<typeof createContext>;
export type WebhookRequest = IncomingMessage & { rawBody: Buffer };
const start = async () => {
const webhookMiddleware = bodyParser.json({
verify: (req: WebhookRequest, _, buffer) => {
req.rawBody = buffer;
},
});
const payload = await getPayloadClient({
initOptions: {
express: app,
onInit: async (cms) => {
cms.logger.info(`Admin URL ${cms.getAdminURL()}`);
},
},
});
app.post("/api/webhooks/stripe", webhookMiddleware, stripeWebhookHandler);
const cartRouter = express.Router();
cartRouter.use(payload.authenticate);
cartRouter.get("/", (req, res) => {
const request = req as PayloadRequest;
if (!request.user) return res.redirect("/sign-in?origin=cart");
const parsedUrl = parse(req.url, true);
return nextApp.render(req, res, "/cart", parsedUrl.query);
});
app.use("/cart", cartRouter);
if (process.env.NEXT_BUILD) {
app.listen(PORT, async () => {
payload.logger.info("Nextjs is building for production");
//@ts-expect-error
await nextBuild(path.join(__dirname, "../"));
process.exit();
});
return;
}
app.use(
"/api/trpc",
trpcExpress.createExpressMiddleware({
router: appRouter,
createContext,
})
);
app.use((req, res) => nextHandler(req, res));
nextApp.prepare().then(() => {
// payload.logger.info("Next js started");
app.listen(PORT, () => {
// payload.logger.info(`Next js Admin URL : ${process.env.NEXT_PUBLIC_SERVER_URL}`);
});
});
};
start();