-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtrpc-pure-client.ts
More file actions
64 lines (58 loc) · 1.75 KB
/
trpc-pure-client.ts
File metadata and controls
64 lines (58 loc) · 1.75 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
/* eslint-disable @typescript-eslint/no-explicit-any */
import { createTrpcClient } from '@analogjs/trpc';
import { inject } from '@angular/core';
import 'isomorphic-fetch';
import superjson from 'superjson';
import { AppRouter } from '../server/trpc/routers/index';
function customPureFetch(
input: RequestInfo | URL,
init?: RequestInit & { method: 'GET' }
) {
if ((globalThis as any).$fetch) {
return (globalThis as any).$fetch
.raw(input.toString(), {
...init,
credentials: 'include', // important for CORS with cookies
headers: {
...(init?.headers || {}),
},
})
.then((response: any) => ({
...response,
headers: response.headers,
json: () => Promise.resolve(response._data),
}));
}
// dev server trpc for analog & nitro
if (typeof window === 'undefined') {
const host =
process.env['NITRO_HOST'] ?? process.env['ANALOG_HOST'] ?? 'localhost';
const port =
process.env['NITRO_PORT'] ?? process.env['ANALOG_PORT'] ?? 4205;
const base = `http://${host}:${port}`;
if (input instanceof Request) {
input = new Request(base, input);
} else {
input = new URL(input, base);
}
}
return fetch(input, {
...init,
credentials: 'include', // important for CORS with cookies
headers: {
...(init?.headers || {}),
},
});
}
export const {
provideTrpcClient: provideTrpcPureClient,
TrpcClient: TrpcPureClient,
TrpcHeaders: TrpcPureHeaders,
} = createTrpcClient<AppRouter>({
url: '/api/trpc',
options: { transformer: superjson },
batchLinkOptions: { fetch: customPureFetch, transformer: superjson } as any, // use custom fetch
});
export function injectTrpcPureClient() {
return inject(TrpcPureClient);
}