2022-09-29 16:58:29 +00:00
|
|
|
import superjson from "superjson";
|
|
|
|
|
|
|
|
import { initTRPC, TRPCError } from "@trpc/server";
|
|
|
|
|
|
|
|
import { Context } from "./createContext";
|
|
|
|
|
2022-11-10 23:40:01 +00:00
|
|
|
const t = initTRPC.context<Context>().create({
|
2022-09-29 16:58:29 +00:00
|
|
|
transformer: superjson,
|
|
|
|
});
|
|
|
|
|
|
|
|
const perfMiddleware = t.middleware(async ({ path, type, next }) => {
|
|
|
|
performance.mark("Start");
|
|
|
|
const result = await next();
|
|
|
|
performance.mark("End");
|
|
|
|
performance.measure(`[${result.ok ? "OK" : "ERROR"}][$1] ${type} '${path}'`, "Start", "End");
|
|
|
|
return result;
|
|
|
|
});
|
|
|
|
|
|
|
|
const isAuthedMiddleware = t.middleware(({ ctx, next }) => {
|
|
|
|
if (!ctx.user || !ctx.session) {
|
|
|
|
throw new TRPCError({ code: "UNAUTHORIZED" });
|
|
|
|
}
|
|
|
|
return next({
|
|
|
|
ctx: {
|
|
|
|
// infers that `user` and `session` are non-nullable to downstream procedures
|
|
|
|
session: ctx.session,
|
|
|
|
user: ctx.user,
|
|
|
|
},
|
|
|
|
});
|
|
|
|
});
|
|
|
|
|
2022-11-10 23:40:01 +00:00
|
|
|
export const router = t.router;
|
|
|
|
export const mergeRouters = t.mergeRouters;
|
|
|
|
export const middleware = t.middleware;
|
2022-09-29 16:58:29 +00:00
|
|
|
export const publicProcedure = t.procedure.use(perfMiddleware);
|
|
|
|
export const authedProcedure = t.procedure.use(perfMiddleware).use(isAuthedMiddleware);
|