trpc.ts46 lines, 1.1 KB
| 1 | import { initTRPC, TRPCError } from "@trpc/server"; |
| 2 | import superjson from "superjson"; |
| 3 | import { ZodError } from "zod"; |
| 4 | import { db } from "../db"; |
| 5 | import { auth } from "../auth"; |
| 6 | |
| 7 | export const createTRPCContext = async (opts: { headers: Headers }) => { |
| 8 | const session = await auth.api.getSession({ headers: opts.headers }); |
| 9 | return { |
| 10 | db, |
| 11 | session, |
| 12 | headers: opts.headers, |
| 13 | }; |
| 14 | }; |
| 15 | |
| 16 | const t = initTRPC.context<typeof createTRPCContext>().create({ |
| 17 | transformer: superjson, |
| 18 | errorFormatter({ shape, error }) { |
| 19 | return { |
| 20 | ...shape, |
| 21 | data: { |
| 22 | ...shape.data, |
| 23 | zodError: |
| 24 | error.cause instanceof ZodError ? error.cause.flatten() : null, |
| 25 | }, |
| 26 | }; |
| 27 | }, |
| 28 | }); |
| 29 | |
| 30 | export const createCallerFactory = t.createCallerFactory; |
| 31 | |
| 32 | export const createTRPCRouter = t.router; |
| 33 | export const publicProcedure = t.procedure; |
| 34 | |
| 35 | export const protectedProcedure = t.procedure.use(async ({ ctx, next }) => { |
| 36 | if (!ctx.session?.user) { |
| 37 | throw new TRPCError({ code: "UNAUTHORIZED" }); |
| 38 | } |
| 39 | return next({ |
| 40 | ctx: { |
| 41 | ...ctx, |
| 42 | session: ctx.session, |
| 43 | user: ctx.session.user, |
| 44 | }, |
| 45 | }); |
| 46 | }); |