-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathorpc.ts
More file actions
64 lines (58 loc) · 1.58 KB
/
orpc.ts
File metadata and controls
64 lines (58 loc) · 1.58 KB
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
63
64
import { os, implement } from '@orpc/server';
import type { AuthInstance } from '@repo/auth/server';
import type { DatabaseInstance } from '@repo/db/client';
import { appContract } from '../contracts';
export const createORPCContext = 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,
};
};
const timingMiddleware = os.middleware(async ({ next, path }) => {
const start = Date.now();
let waitMsDisplay = '';
if (process.env.NODE_ENV !== 'production') {
// 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[RPC] /${path.join('/')} executed after ${end - start}ms${waitMsDisplay}`,
);
return result;
});
const base = implement(appContract);
export const publicProcedure = base
.$context<Awaited<ReturnType<typeof createORPCContext>>>()
.use(timingMiddleware);
export const protectedProcedure = publicProcedure.use(
({ context, next, errors }) => {
if (!context.session?.user) {
throw errors.UNAUTHORIZED({
message: 'Missing user session. Please log in!',
});
}
return next({
context: {
session: { ...context.session },
},
});
},
);