You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
54 lines
2.1 KiB
TypeScript
54 lines
2.1 KiB
TypeScript
import { appRouter } from "./trpc/router";
|
|
// TODO: stop using universal-middleware and directly integrate server middlewares instead and/or use vike-server https://vike.dev/server. (Bati generates boilerplates that use universal-middleware https://github.com/magne4000/universal-middleware to make Bati's internal logic easier. This is temporary and will be removed soon.)
|
|
import {
|
|
type Get,
|
|
type UniversalHandler,
|
|
env as getEnv,
|
|
} from "@universal-middleware/core";
|
|
import { fetchRequestHandler } from "@trpc/server/adapters/fetch";
|
|
import { getDbClient } from "../database/postgres";
|
|
import { createOpenRouter } from "@openrouter/ai-sdk-provider";
|
|
import { env as processEnv } from "./env.js";
|
|
import { getToken } from "@auth/core/jwt";
|
|
|
|
export const trpcHandler = ((endpoint) => (request, context, runtime) => {
|
|
return fetchRequestHandler({
|
|
endpoint,
|
|
req: request,
|
|
router: appRouter,
|
|
async createContext({ req, resHeaders }) {
|
|
const env = getEnv(runtime);
|
|
const dbClient = getDbClient(
|
|
(env.POSTGRES_CONNECTION_STRING ||
|
|
processEnv.POSTGRES_CONNECTION_STRING) as string
|
|
);
|
|
const openrouter = createOpenRouter({
|
|
apiKey: (env.OPENROUTER_API_KEY ||
|
|
processEnv.OPENROUTER_API_KEY) as string,
|
|
});
|
|
const jwt = await getToken({
|
|
req,
|
|
secret: (env.AUTHJS_SECRET || processEnv.AUTHJS_SECRET) as string,
|
|
/** Needed to specify cookie name because for some reason in production
|
|
* it wasn't reading the correct cookie but in development it was. It
|
|
* was not straightforward to fix the name of the cookie in
|
|
* `authOptions`, so I adjusted what cookie to read from here: */
|
|
cookieName:
|
|
env.NODE_ENV === "production"
|
|
? "__Secure-authjs.session-token"
|
|
: "authjs.session-token",
|
|
});
|
|
return {
|
|
...context,
|
|
...runtime,
|
|
req,
|
|
resHeaders,
|
|
dbClient,
|
|
openrouter,
|
|
jwt,
|
|
};
|
|
},
|
|
allowMethodOverride: true,
|
|
});
|
|
}) satisfies Get<[endpoint: string], UniversalHandler>;
|