-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathtrpc.ts
62 lines (55 loc) · 1.49 KB
/
trpc.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import { initTRPC, TRPCError } from '@trpc/server';
import SuperJSON from 'superjson';
import type { AuthInstance } from '@repo/auth/server';
import type { DatabaseInstance } from '@repo/db/client';
export const createTRPCContext = async ({
auth,
db,
headers,
}: {
auth: AuthInstance;
db: DatabaseInstance;
headers: Headers;
}): Promise<{
db: DatabaseInstance;
session: AuthInstance['$Infer']['Session'] | null;
}> => {
const session = await auth.api.getSession({
headers,
});
return {
db,
session,
};
};
export const t = initTRPC.context<typeof createTRPCContext>().create({
transformer: SuperJSON,
});
export const router = t.router;
const timingMiddleware = t.middleware(async ({ next, path }) => {
const start = Date.now();
let waitMsDisplay = '';
if (t._config.isDev) {
// artificial delay in dev 100-500ms
const waitMs = Math.floor(Math.random() * 400) + 100;
await new Promise((resolve) => setTimeout(resolve, waitMs));
waitMsDisplay = ` (artificial delay: ${waitMs}ms)`;
}
const result = await next();
const end = Date.now();
console.log(
`\t[TRPC] /${path} executed after ${end - start}ms${waitMsDisplay}`,
);
return result;
});
export const publicProcedure = t.procedure.use(timingMiddleware);
export const protectedProcedure = publicProcedure.use(({ ctx, next }) => {
if (!ctx.session?.user) {
throw new TRPCError({ code: 'FORBIDDEN' });
}
return next({
ctx: {
session: { ...ctx.session },
},
});
});