46 lines
1.1 KiB
TypeScript
46 lines
1.1 KiB
TypeScript
|
|
import { initTRPC, TRPCError } from "@trpc/server";
|
||
|
|
import superjson from "superjson";
|
||
|
|
import type { Session } from "next-auth";
|
||
|
|
import { db } from "@tasks/database";
|
||
|
|
import { auth } from "@/lib/auth";
|
||
|
|
|
||
|
|
export type Context = {
|
||
|
|
db: typeof db;
|
||
|
|
session: Session | null;
|
||
|
|
};
|
||
|
|
|
||
|
|
export async function createContext(): Promise<Context> {
|
||
|
|
try {
|
||
|
|
const session = await auth();
|
||
|
|
return { db, session };
|
||
|
|
} catch (error) {
|
||
|
|
console.error("[trpc] createContext failed:", error);
|
||
|
|
throw new TRPCError({
|
||
|
|
code: "INTERNAL_SERVER_ERROR",
|
||
|
|
message: "Failed to create request context",
|
||
|
|
cause: error,
|
||
|
|
});
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
const t = initTRPC.context<Context>().create({
|
||
|
|
transformer: superjson,
|
||
|
|
});
|
||
|
|
|
||
|
|
export const isAuthed = t.middleware(({ ctx, next }) => {
|
||
|
|
if (!ctx.session?.user) {
|
||
|
|
throw new TRPCError({ code: "UNAUTHORIZED" });
|
||
|
|
}
|
||
|
|
return next({
|
||
|
|
ctx: {
|
||
|
|
...ctx,
|
||
|
|
session: ctx.session,
|
||
|
|
},
|
||
|
|
});
|
||
|
|
});
|
||
|
|
|
||
|
|
export const router = t.router;
|
||
|
|
export const createCallerFactory = t.createCallerFactory;
|
||
|
|
export const publicProcedure = t.procedure;
|
||
|
|
export const protectedProcedure = t.procedure.use(isAuthed);
|