/
client.ts
414 lines (370 loc) · 10.2 KB
/
client.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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
import { AppRoute, AppRouteMutation, AppRouter, isAppRoute } from './dsl';
import { insertParamsIntoPath } from './paths';
import { convertQueryParamsToUrlString } from './query';
import { AreAllPropertiesOptional, Prettify } from './type-utils';
import { UnknownStatusError } from './unknown-status-error';
import {
ClientInferRequest,
ClientInferResponses,
PartialClientInferRequest,
} from './infer-types';
import { isZodType } from './zod-utils';
import { Equal, Expect } from './test-helpers';
type RecursiveProxyObj<T extends AppRouter, TClientArgs extends ClientArgs> = {
[TKey in keyof T]: T[TKey] extends AppRoute
? AppRouteFunction<T[TKey], TClientArgs>
: T[TKey] extends AppRouter
? RecursiveProxyObj<T[TKey], TClientArgs>
: never;
};
/**
* @deprecated Only safe to use on the client-side. Use `ServerInferResponses`/`ClientInferResponses` instead.
*/
export type ApiResponseForRoute<T extends AppRoute> = ClientInferResponses<T>;
/**
* @deprecated Only safe to use on the client-side. Use `ServerInferResponses`/`ClientInferResponses` instead.
*/
export function getRouteResponses<T extends AppRouter>(router: T) {
return {} as ClientInferResponses<T>;
}
/**
* Returned from a mutation or query call
*/
export type AppRouteFunction<
TRoute extends AppRoute,
TClientArgs extends ClientArgs,
TArgs = PartialClientInferRequest<TRoute, TClientArgs>,
> = AreAllPropertiesOptional<TArgs> extends true
? (args?: Prettify<TArgs>) => Promise<Prettify<ClientInferResponses<TRoute>>>
: (args: Prettify<TArgs>) => Promise<Prettify<ClientInferResponses<TRoute>>>;
export type FetchOptions = Omit<RequestInit, 'method' | 'headers' | 'body'>;
export interface OverrideableClientArgs {
baseUrl: string;
credentials?: RequestCredentials;
jsonQuery?: boolean;
validateResponse?: boolean;
}
export interface ClientArgs extends OverrideableClientArgs {
baseHeaders?: Record<string, string>;
api?: ApiFetcher;
}
export type ApiFetcherArgs = {
route: AppRoute;
path: string;
method: string;
headers: Record<string, string>;
body: FormData | URLSearchParams | string | null | undefined;
rawBody: unknown;
rawQuery: unknown;
contentType: AppRouteMutation['contentType'];
fetchOptions?: FetchOptions;
validateResponse?: boolean;
/**
* @deprecated Use `fetchOptions.credentials` instead
*/
credentials?: RequestCredentials;
/**
* @deprecated Use `fetchOptions.signal` instead
*/
signal?: AbortSignal;
/**
* @deprecated Use `fetchOptions.cache` instead
*/
cache?: RequestCache;
/**
* @deprecated Use `fetchOptions.next` instead
*/
next?: { revalidate?: number | false; tags?: string[] } | undefined;
};
export type ApiFetcher = (args: ApiFetcherArgs) => Promise<{
status: number;
body: unknown;
headers: Headers;
}>;
/**
* Default fetch api implementation:
*
* Can be used as a reference for implementing your own fetcher,
* or used in the "api" field of ClientArgs to allow you to hook
* into the request to run custom logic
*/
export const tsRestFetchApi: ApiFetcher = async ({
route,
path,
method,
headers,
body,
validateResponse,
fetchOptions,
}) => {
const result = await fetch(path, {
...fetchOptions,
method,
headers,
body,
});
const contentType = result.headers.get('content-type');
if (contentType?.includes('application/') && contentType?.includes('json')) {
const response = {
status: result.status,
body: await result.json(),
headers: result.headers,
};
const responseSchema = route.responses[response.status];
if (
(validateResponse ?? route.validateResponseOnClient) &&
isZodType(responseSchema)
) {
return {
...response,
body: responseSchema.parse(response.body),
};
}
return response;
}
if (contentType?.includes('text/')) {
return {
status: result.status,
body: await result.text(),
headers: result.headers,
};
}
return {
status: result.status,
body: await result.blob(),
headers: result.headers,
};
};
const createFormData = (body: unknown) => {
const formData = new FormData();
const appendToFormData = (key: string, value: unknown) => {
if (value instanceof File) {
formData.append(key, value);
} else {
formData.append(key, JSON.stringify(value));
}
};
Object.entries(body as Record<string, unknown>).forEach(([key, value]) => {
if (Array.isArray(value)) {
for (const item of value) {
appendToFormData(key, item);
}
} else {
appendToFormData(key, value);
}
});
return formData;
};
const normalizeHeaders = (headers: Record<string, string | undefined>) => {
return Object.fromEntries(
Object.entries(headers).map(([k, v]) => [k.toLowerCase(), v]),
);
};
export const fetchApi = ({
path,
clientArgs,
route,
body,
query,
extraInputArgs,
headers,
fetchOptions,
}: {
path: string;
clientArgs: ClientArgs;
route: AppRoute;
query: unknown;
body: unknown;
extraInputArgs: Record<string, unknown>;
headers: Record<string, string | undefined>;
fetchOptions?: FetchOptions;
}) => {
const apiFetcher = clientArgs.api || tsRestFetchApi;
const combinedHeaders = {
...(clientArgs.baseHeaders && normalizeHeaders(clientArgs.baseHeaders)),
...normalizeHeaders(headers),
} as Record<string, string>;
// Remove any headers that are set to undefined
Object.keys(combinedHeaders).forEach((key) => {
if (combinedHeaders[key] === undefined) {
delete combinedHeaders[key];
}
});
let fetcherArgs: ApiFetcherArgs = {
route,
path,
method: route.method,
headers: combinedHeaders,
body: undefined,
rawBody: body,
rawQuery: query,
contentType: undefined,
validateResponse: clientArgs.validateResponse,
fetchOptions: {
...(clientArgs.credentials && { credentials: clientArgs.credentials }),
...fetchOptions,
},
...(fetchOptions?.signal && { signal: fetchOptions.signal }),
...(fetchOptions?.cache && { cache: fetchOptions.cache }),
...(fetchOptions &&
'next' in fetchOptions &&
!!fetchOptions?.next && { next: fetchOptions.next }),
};
if (route.method !== 'GET') {
if (route.contentType === 'multipart/form-data') {
fetcherArgs = {
...fetcherArgs,
contentType: 'multipart/form-data',
body: body instanceof FormData ? body : createFormData(body),
};
} else if (route.contentType === 'application/x-www-form-urlencoded') {
fetcherArgs = {
...fetcherArgs,
contentType: 'application/x-www-form-urlencoded',
headers: {
'content-type': 'application/x-www-form-urlencoded',
...fetcherArgs.headers,
},
body:
typeof body === 'string'
? body
: new URLSearchParams(
body as Record<string, string> | URLSearchParams,
),
};
} else if (body !== null && body !== undefined) {
fetcherArgs = {
...fetcherArgs,
contentType: 'application/json',
headers: {
'content-type': 'application/json',
...fetcherArgs.headers,
},
body: JSON.stringify(body),
};
}
}
return apiFetcher({
...fetcherArgs,
...extraInputArgs,
});
};
export const evaluateFetchApiArgs = <TAppRoute extends AppRoute>(
route: TAppRoute,
clientArgs: InitClientArgs,
inputArgs?: ClientInferRequest<AppRouteMutation, ClientArgs>,
) => {
const {
query,
params,
body,
headers,
extraHeaders,
overrideClientOptions,
fetchOptions,
// TODO: remove in 4.0
cache,
// TODO: remove in 4.0
next,
// extra input args
...extraInputArgs
} =
(inputArgs as ClientInferRequest<AppRouteMutation, ClientArgs> & {
next?: any;
}) || {};
// assert that we removed all non-extra args
// eslint-disable-next-line @typescript-eslint/no-unused-vars
type AssertExtraInputArgsEmpty = Expect<Equal<typeof extraInputArgs, {}>>;
const overriddenClientArgs = {
...clientArgs,
...overrideClientOptions,
};
const completeUrl = getCompleteUrl(
query,
overriddenClientArgs.baseUrl,
params,
route,
!!overriddenClientArgs.jsonQuery,
);
return {
path: completeUrl,
clientArgs: overriddenClientArgs,
route,
body,
query,
extraInputArgs,
fetchOptions: {
...(cache && { cache }),
...(next && { next }),
...fetchOptions,
},
headers: {
...extraHeaders,
...headers,
},
} as Parameters<typeof fetchApi>[0];
};
/**
* @hidden
*/
export const getCompleteUrl = (
query: unknown,
baseUrl: string,
params: unknown,
route: AppRoute,
jsonQuery: boolean,
) => {
const path = insertParamsIntoPath({
path: route.path,
params: params as any,
});
const queryComponent = convertQueryParamsToUrlString(query, jsonQuery);
return `${baseUrl}${path}${queryComponent}`;
};
export const getRouteQuery = <TAppRoute extends AppRoute>(
route: TAppRoute,
clientArgs: InitClientArgs,
) => {
const knownResponseStatuses = Object.keys(route.responses);
return async (
inputArgs?: ClientInferRequest<AppRouteMutation, ClientArgs>,
) => {
const fetchApiArgs = evaluateFetchApiArgs(route, clientArgs, inputArgs);
const response = await fetchApi(fetchApiArgs);
if (!clientArgs.throwOnUnknownStatus) {
return response;
}
if (knownResponseStatuses.includes(response.status.toString())) {
return response;
}
throw new UnknownStatusError(response, knownResponseStatuses);
};
};
export type InitClientReturn<
T extends AppRouter,
TClientArgs extends ClientArgs,
> = RecursiveProxyObj<T, TClientArgs>;
export type InitClientArgs = ClientArgs & {
/**
* Ensures that the responses from the server match those defined in the
* contract.
*/
throwOnUnknownStatus?: boolean;
};
export const initClient = <
T extends AppRouter,
TClientArgs extends InitClientArgs,
>(
router: T,
args: TClientArgs,
): InitClientReturn<T, TClientArgs> => {
return Object.fromEntries(
Object.entries(router).map(([key, subRouter]) => {
if (isAppRoute(subRouter)) {
return [key, getRouteQuery(subRouter, args)];
} else {
return [key, initClient(subRouter, args)];
}
}),
);
};