forked from DeepNotesApp/DeepNotes
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtrpc.ts
More file actions
71 lines (54 loc) · 1.62 KB
/
trpc.ts
File metadata and controls
71 lines (54 loc) · 1.62 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
65
66
67
68
69
70
71
import type { AppRouter } from '@deepnotes/app-server/src/trpc/router';
import { createTRPCProxyClient, httpLink } from '@trpc/client';
import { once } from 'lodash';
import superjson from 'superjson';
let nodeFetch: () => Promise<typeof fetch>;
if (process.env.SERVER) {
nodeFetch = once(
async () => (await import('node-fetch')).default as unknown as typeof fetch,
);
}
export const trpcClient = createTRPCProxyClient<AppRouter>({
transformer: superjson,
links: [
httpLink({
url: process.env.APP_SERVER_URL,
headers({ op }) {
return {
...(op.context as any)?.headers,
'X-Trpc-Context': op.context,
};
},
async fetch(url, options) {
// Extract context
let context;
if ((options?.headers as any)?.['X-Trpc-Context'] != null) {
context = (options?.headers as any)?.['X-Trpc-Context'];
delete (options?.headers as any)?.['X-Trpc-Context'];
}
// Fetch
let response;
if (process.env.SERVER) {
response = await (await nodeFetch())(url, options);
} else {
response = await fetch(url, {
...options,
credentials: 'include',
});
}
// Pass SSR cookies to browser
if (
process.env.SERVER &&
response.headers.has('set-cookie') &&
context?.ssrContext != null
) {
context.ssrContext.res.setHeader(
'set-cookie',
response.headers.get('set-cookie')!.split(/, (?=\w+=)/g),
);
}
return response;
},
}),
],
});