import { TRPCError, initTRPC } from "@trpc/server";
import superjson from "superjson";
import { type CreateNextContextOptions } from "@trpc/server/adapters/next";
import { getServerAuthSession } from "./auth";
import { Session } from "next-auth";
type CreateContextOptions = {
session: Session | null;
};
const createInnerTRPCContext = (opts: CreateContextOptions) => {
return {
session: opts.session,
//prisma,
};
};
export const createTRPCContext = async (opts: CreateNextContextOptions) => {
const { req, res } = opts;
const session = await getServerAuthSession({ req, res });
return createInnerTRPCContext({
session,
});
};
const t = initTRPC.context<typeof createTRPCContext>().create({
transformer: superjson,
});
const isAuthed = t.middleware(({ ctx, next }: any) => {
if (!ctx.session || !ctx.session.user) {
throw new TRPCError({ code: "UNAUTHORIZED" });
}
return next({
ctx: {
session: { ...ctx.session, user: ctx.session.user },
},
});
});
export const router = t.router;
export const protectedProcedure = t.procedure.use(isAuthed);
export const publicProcedure = t.procedure;