import { TRPCError, type inferAsyncReturnType, initTRPC } from "@trpc/server";
import { type CreateNextContextOptions } from "@trpc/server/adapters/next";
import { getAuth, type SignedInAuthObject, type SignedOutAuthObject } from '@clerk/nextjs/server';
import superjson from "superjson";
import { ZodError } from "zod";
import { prisma } from "~/server/prisma";
type CreateContextOptions = Record<string, never>;
interface AuthContext {
auth: SignedInAuthObject | SignedOutAuthObject;
}
export const createContextInner = async ({ auth }: AuthContext ) => {
return {
auth,
}
}
// const createInnerTRPCContext = (_opts: CreateContextOptions) => {
// return {
// prisma,
// };
// };
// export const createTRPCContext = (opts: CreateNextContextOptions) => {
// return {
// ...createInnerTRPCContext({}),
// req: opts.req,
// };
// };
export const createContext = async (opts: CreateNextContextOptions) => {
return await createContextInner({ auth: getAuth(opts.req) })
}
const t = initTRPC.context<Context>().create({
transformer: superjson,
errorFormatter({ shape }) {
return shape
}
})
export const createTRPCRouter = t.router;
export type Context = inferAsyncReturnType<typeof createContext>;
export const publicProcedure = t.procedure;
const isAuthed = t.middleware(({ next, ctx }) => {
if (!ctx.auth.userId) {
throw new TRPCError({ code: 'UNAUTHORIZED' })
}
return next({
ctx: {
auth: ctx.auth,
},
})
})
// export this procedure to be used anywhere in your application
export const protectedProcedure = t.procedure.use(isAuthed)
export const mergeRouters = t.mergeRouters;