app-template/packages/trpc/src/server.ts

46 lines
1.5 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* 独立 tRPC HTTP 入口(`yarn dev:api`,默认 PORT=4000)。
* web SSR 内嵌 `/api/trpc` 时通常不需要跑本文件。
*
* 注意:必须先副作用加载根 .env,再 import 会读 process.env 的模块(ESM 导入会提升)。
*/
import "./load-env.js";
import { createHTTPServer } from "@trpc/server/adapters/standalone";
import { appRouter } from "./router/index.js";
import { COOKIE_SESSION } from "@app/types";
const port = Number(process.env["PORT"] ?? 4000);
function parseCookies(header: string | null): Record<string, string> {
const out: Record<string, string> = {};
if (!header) return out;
for (const part of header.split(";")) {
const eq = part.indexOf("=");
if (eq < 0) continue;
const key = part.slice(0, eq).trim();
const val = part.slice(eq + 1).trim();
if (key) out[key] = decodeURIComponent(val);
}
return out;
}
const server = createHTTPServer({
router: appRouter,
createContext: ({ req }) => {
const cookies = parseCookies(req.headers.cookie ?? null);
const setCookies: string[] = [];
// standalone 适配器不易注入响应头;session cookie 以内嵌 /api/trpc 为准
void setCookies;
return {
sessionToken: cookies[COOKIE_SESSION],
setCookie: (value: string) => {
setCookies.push(value);
},
};
},
});
server.listen(port, () => {
console.log(`[trpc] listening on http://localhost:${port}`);
});