Files
coolify/apps/server/src/trpc/trpc.ts
Andras Bacsai 2009dc11db wip trpc
2022-12-12 14:48:56 +01:00

34 lines
920 B
TypeScript

import { initTRPC, TRPCError } from '@trpc/server';
import superjson from 'superjson';
import type { Context } from './context';
const t = initTRPC.context<Context>().create({
transformer: superjson,
errorFormatter({ shape }) {
return shape;
}
});
const logger = t.middleware(async ({ path, type, next }) => {
const start = Date.now();
const result = await next();
const durationMs = Date.now() - start;
result.ok
? console.log('OK request timing:', { path, type, durationMs })
: console.log('Non-OK request timing', { path, type, durationMs });
return result;
});
const isAdmin = t.middleware(async ({ ctx, next }) => {
if (!ctx.user) {
throw new TRPCError({ code: 'UNAUTHORIZED' });
}
return next({
ctx: {
user: ctx.user
}
});
});
export const router = t.router;
export const privateProcedure = t.procedure.use(isAdmin).use(logger);
export const publicProcedure = t.procedure.use(logger);