-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathapiURL.ts
More file actions
531 lines (486 loc) · 15.3 KB
/
apiURL.ts
File metadata and controls
531 lines (486 loc) · 15.3 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
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
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
import { UnknownApiResponse } from "@/lib/api/common/apiResponse";
import { operations, paths } from "@/lib/api/types/schema";
import { If, Split } from "type-fest";
type MaybeParams<T> =
keyof T extends never ? { params?: undefined } : { params: T };
type PathSegments<T extends string> = Split<T, "/">;
type ExtractParams<T extends string> =
T extends `${infer _Before}{${infer Param}}${infer After}` ?
[Param, ...ExtractParams<After>]
: [];
type ParamsToStrings<T extends readonly string[]> = {
[K in keyof T]: string;
};
type ResolveSegment<T extends string> = T extends `{${string}}` ? string : T;
type ResolvePath<T extends readonly string[]> = {
[K in keyof T]: T[K] extends string ? ResolveSegment<T[K]> : T[K];
};
type CleanPath<T extends string> = T extends `/${infer Rest}` ? Rest : T;
type CollectAllSegments<S extends string, Acc extends string = ""> =
S extends `${infer Head}/${infer Tail}` ?
`${Acc}/${Head}` | CollectAllSegments<Tail, `${Acc}/${Head}`>
: `${Acc}/${S}`;
type AllPathSegents<TKey extends PathsKey> = CollectAllSegments<
CleanPath<TKey>
>;
type HttpMethodLower =
| "get"
| "post"
| "put"
| "delete"
| "options"
| "head"
| "patch"
| "trace";
type HttpMethodUpper = Uppercase<HttpMethodLower>;
type PathsKey = keyof paths;
type PathsMethods<TKey extends PathsKey> = paths[TKey];
type PathsMethodKey<TKey extends PathsKey> = keyof PathsMethods<TKey>;
type PathMethodResult<
TPathKey extends PathsKey,
TPathMethodKey extends PathsMethodKey<TPathKey>,
> = PathsMethods<TPathKey>[TPathMethodKey];
type OperationsKey = keyof operations;
type OperationsPath<TKey extends OperationsKey> = operations[TKey];
type OperationFromPathMethodResult<TResult> = {
[K in OperationsKey]: OperationsPath<K> extends TResult ? K : never;
}[OperationsKey];
type PathParamToOperations<
TPathKey extends PathsKey,
TMethod extends PathsMethodKey<TPathKey>,
> = OperationFromPathMethodResult<PathMethodResult<TPathKey, TMethod>>;
type PathOperationsToPathParams<TOperationsKey extends OperationsKey> =
OperationsPath<TOperationsKey>["parameters"]["path"];
type PathOperationsToPathQueries<TOperationsKey extends OperationsKey> =
OperationsPath<TOperationsKey>["parameters"]["query"];
type PathOperationsToPathResponseContent<TOperationsKey extends OperationsKey> =
Extract<
OperationsPath<TOperationsKey>["responses"],
{ 200: unknown }
>[200]["content"];
type PathOperationsToPathResponseBody<TOperationsKey extends OperationsKey> =
If<
Extract<
PathOperationsToPathResponseContent<TOperationsKey>,
{ "*/*": unknown }
> extends never ?
true
: false,
Extract<
PathOperationsToPathResponseContent<TOperationsKey>,
{ "text/event-stream": unknown }
>["text/event-stream"],
Extract<
PathOperationsToPathResponseContent<TOperationsKey>,
{ "*/*": unknown }
>["*/*"]
>;
type PathOperationsToPathResponsePayload<TOperationsKey extends OperationsKey> =
Extract<
PathOperationsToPathResponseBody<TOperationsKey>,
{ payload: unknown }
>["payload"];
type PathOperationsToPathRequestBody<TOperationsKey extends OperationsKey> =
Extract<
OperationsPath<TOperationsKey>["requestBody"],
{ content: unknown }
>["content"]["application/json"];
/**
* The de-facto type-safe object to fetch data from the Codebloom backend.
* This class introspects the autogenerated schema types file that is based on
* the OpenAPI schema from the backend.
*
* @example
* ```ts
const { url, method, req, res } = ApiURL.create("/api/admin/user/admin/toggle", {
method: "POST",
});
const response = await fetch(url, {
method: method,
headers: {
"Content-Type": "application/json",
},
body: req({
id: userId,
toggleTo,
}),
});
const json = res(await response.json());
* ```
*/
export class ApiURL<
TPathKey extends PathsKey,
TPathMethod extends PathsMethodKey<TPathKey>,
> {
private readonly _url: URL;
private readonly _method: Uppercase<
Extract<PathsMethodKey<TPathKey>, string>
>;
private readonly _key: readonly [
...PathSegments<CleanPath<TPathKey>>,
{
method: TPathMethod;
params: PathOperationsToPathParams<
PathParamToOperations<TPathKey, TPathMethod>
> | null;
queries: PathOperationsToPathQueries<
PathParamToOperations<TPathKey, TPathMethod>
> | null;
},
];
private static _generateKey<
const TGeneratePathKey extends PathsKey,
const TGeneratePathMethod extends PathsMethodKey<TGeneratePathKey>,
>(
path: TGeneratePathKey,
{
method,
params,
queries,
}: {
method: TGeneratePathMethod;
} & MaybeParams<
PathOperationsToPathParams<
PathParamToOperations<TGeneratePathKey, TGeneratePathMethod>
>
> & {
queries?: PathOperationsToPathQueries<
PathParamToOperations<TGeneratePathKey, TGeneratePathMethod>
>;
},
): readonly [
...PathSegments<CleanPath<TGeneratePathKey>>,
{
method: TGeneratePathMethod;
params: PathOperationsToPathParams<
PathParamToOperations<TGeneratePathKey, TGeneratePathMethod>
> | null;
queries: PathOperationsToPathQueries<
PathParamToOperations<TGeneratePathKey, TGeneratePathMethod>
> | null;
},
] {
let resolved: string = path;
if (params) {
for (const [k, v] of Object.entries(params)) {
resolved = resolved.replace(`{${k}}`, encodeURIComponent(String(v)));
}
}
const segments = resolved
.split("/")
.filter((segment) => segment.length > 0);
return [
...(segments as PathSegments<CleanPath<TGeneratePathKey>>),
{
method: method,
params: (params && Object.typedKeys(params ?? {}).length ?
params
: null) as PathOperationsToPathParams<
PathParamToOperations<TGeneratePathKey, TGeneratePathMethod>
> | null,
queries: (queries && Object.typedKeys(queries ?? {}).length ?
queries
: null) as PathOperationsToPathQueries<
PathParamToOperations<TGeneratePathKey, TGeneratePathMethod>
> | null,
},
];
}
/**
* Static factory method to create an `ApiURL`.
*
* @param path - The API URL.
* @param {Object} options - Configuration options for the factory.
* @param {TCreatePathMethod | PathsKey} options.method - What method will be used for the request.
* @param {Object} options.params - An object where each key is a path on the URL **IF URL IS DYNAMIC**. If URL is not dynamic, it can stay undefined with no errors thrown.
* @param {Object} options.queries - An object where each key is a query param on the URL.
*
* @example
* ```ts
// url has Intellisense, try it!
const { url, method, req, res } = ApiURL.create("/api/admin/user/admin/toggle", {
method: "POST", // must be a valid method type. If the method doesn't exist in the backend, will throw error.
});
// pass url into `fetch` (`URL` is actually natively supported by `fetch`).
const response = await fetch(url, {
// pass method into `fetch` to avoid duplication
method: method,
// if the backend accepts a body, `req` will validate that what you pass in is what the backend expects.
body: req({
id: userId,
toggleTo,
}),
});
// pass `await response.json()` into the `res` function to get automatic type-safety on the response.
const json = res(await response.json());
* ```
*/
static create<
const TCreatePathKey extends PathsKey,
const TCreatePathMethod extends HttpMethodUpper &
Uppercase<Extract<PathsMethodKey<TCreatePathKey>, string>>,
>(
path: TCreatePathKey,
opts: {
method: TCreatePathMethod;
} & MaybeParams<
PathOperationsToPathParams<
PathParamToOperations<TCreatePathKey, Lowercase<TCreatePathMethod>>
>
> & {
queries?: PathOperationsToPathQueries<
PathParamToOperations<TCreatePathKey, Lowercase<TCreatePathMethod>>
>;
},
): ApiURL<TCreatePathKey, Lowercase<TCreatePathMethod>> {
const opt = {
...opts,
method: opts.method?.toLowerCase() as Lowercase<TCreatePathMethod>,
};
return new ApiURL(path, opt);
}
private constructor(
path: TPathKey,
options: {
method: TPathMethod;
} & MaybeParams<
PathOperationsToPathParams<PathParamToOperations<TPathKey, TPathMethod>>
> & {
queries?: PathOperationsToPathQueries<
PathParamToOperations<TPathKey, TPathMethod>
>;
},
) {
const { method, params, queries } = options;
this._method = String(method).toUpperCase() as Uppercase<
Extract<keyof PathsMethods<TPathKey>, string>
>;
this._key = ApiURL._generateKey(path, options);
let resolved: string = path;
if (params) {
for (const [k, v] of Object.entries(params)) {
resolved = resolved.replace(`{${k}}`, encodeURIComponent(String(v)));
}
if (/\{[^}]+\}/.test(resolved)) {
throw new Error(`Missing path params for: ${path}`);
}
}
let url: URL;
try {
url = new URL(resolved, window.location.origin);
} catch (e) {
console.log(e);
throw e;
}
this._url = url;
if (!queries) {
return;
}
for (const [k, v] of Object.entries(queries)) {
if (v !== null && v !== undefined) {
url.searchParams.set(k, String(v));
}
}
}
/**
* Return final URL state post-creation of dynamic paths and URL query params. You can
* pass this into `fetch`.
*
* @returns {URL} url - The browser `URL` object.
*
* @example
* ```
const { url } = ApiURL.create(//...);
const response = await fetch(url); // The `URL` object is natively supported by `fetch`.
```
*/
get url(): URL {
return this._url;
}
/**
* Return the `method` passed into the input object, as a way to define `method` on `fetch`.
*
* @returns {typeof this._method} method - The method of the request.
*
* @example
* ```
const { url, method } = ApiURL.create(//...);
const response = await fetch(url, {
method, // will set `fetch.options.method` to `ApiURL.create.method`
});
```
*/
get method(): typeof this._method {
return this._method;
}
/**
* Validate `body` fields on `fetch` based on the body the endpoint would expect.
*
* @returns {string} stringified - Calls `JSON.stringify(body)` under the hood, but adds types from the
* given backend endpoint.
*
* @example
* ```
const { url, method, req } = ApiURL.create(//...);
const response = await fetch(url, {
method,
body: req({
id: user.id // will validate that `id` exists and `user.id` matches the type it wants.
})
});
```
*/
req(
body: PathOperationsToPathRequestBody<
PathParamToOperations<TPathKey, TPathMethod>
>,
): string {
return JSON.stringify(body);
}
/**
* Validate `response.json()` at compile-time, with no real overhead.
*
* @note - This is a no-op, it doesn't do anything in the implementation except return what you passed in
* as an input. However, it is required in order to gain full type-safety.
*
* @returns {string} stringified - Calls `JSON.stringify(body)` under the hood, but adds types from the
* given backend endpoint.
*
* @example
* ```
const { url, res } = ApiURL.create(//...);
const response = await fetch(url, {
// ...
});
const json = res(await response.json()); // json is fully typed at compile-time.
```
*/
res(
response: unknown,
): UnknownApiResponse<
PathOperationsToPathResponsePayload<
PathParamToOperations<TPathKey, TPathMethod>
>
> {
return response as UnknownApiResponse<
PathOperationsToPathResponsePayload<
PathParamToOperations<TPathKey, TPathMethod>
>
>;
}
/**
* Generate a React Query invalidation key that can instead be an API prefix
* instead of a hard URL that can be generated by `ApiURL.queryKey`
*
* @param prefix - The API URL prefix path.
* @param params - Values to replace dynamic paths (e.g., `{id}`) in the order they appear.
*
* @returns an array of strings suitable for use as a React Query invalidaton key.
*
* @example
* ```ts
* useMutation({
* mutationFn: async () => {
* // ...
* },
* onSuccess: () => {
* // static prefix
* queryClient.invalidateQueries({
* queryKey: ApiURL.prefix("/api/leaderboard"),
* });
*
* // dynamic prefix with path params, will error if `id` is not passed in as 2nd param.
* queryClient.invalidateQueries({
* queryKey: ApiURL.prefix("/api/user/{id}", "123"),
* });
* },
* });
* ```
*/
static prefix<
const TPrefixPathKey extends PathsKey,
const TPrefix extends AllPathSegents<TPrefixPathKey>,
>(prefix: TPrefix, ...params: ParamsToStrings<ExtractParams<TPrefix>>) {
let resolved: string = prefix;
for (const param of params) {
resolved = resolved.replace(/\{[^}]+\}/, encodeURIComponent(param));
}
if (/\{[^}]+\}/.test(resolved)) {
throw new Error(`Missing path params for: ${prefix}`);
}
return resolved.split("/").filter((s) => s.length > 0) as readonly [
...ResolvePath<PathSegments<CleanPath<TPrefix>>>,
];
}
/**
* Generate a React Query `queryKey` for caching and invalidation.
*
* @param path - The API URL path.
* @param {Object} options - Configuration options.
* @param {TQKPathMethod} options.method - The HTTP method.
* @param {Object} options.params - Path parameters (if URL is dynamic).
* @param {Object} options.queries - Query parameters.
*
* @returns An array suitable for use as a React Query key, with path segments split by "/".
*
* @example
* ```ts
* useMutation({
* mutationFn: () => { ... },
* onSuccess: () => {
* queryClient.invalidateQueries({ queryKey: ApiURL.key("/api/auth/validate"), {
* method: "GET",
* }})
* }
* });
* ```
*/
static queryKey<
const TQKPathKey extends PathsKey,
const TQKPathMethod extends HttpMethodUpper &
Uppercase<Extract<PathsMethodKey<TQKPathKey>, string>>,
>(
path: TQKPathKey,
options: {
method: TQKPathMethod;
} & MaybeParams<
PathOperationsToPathParams<
PathParamToOperations<TQKPathKey, Lowercase<TQKPathMethod>>
>
> & {
queries?: PathOperationsToPathQueries<
PathParamToOperations<TQKPathKey, Lowercase<TQKPathMethod>>
>;
},
) {
const opts = {
...options,
method: options.method.toLowerCase() as Lowercase<TQKPathMethod>,
};
return ApiURL._generateKey(path, opts);
}
/**
* Get the React Query key for this instance.
*
* @returns The query key array for this API URL instance.
*
* @example
* ```ts
* const api = ApiURL.create("/api/user/{id}", {
* method: "GET",
* params: { id: "123" },
* });
*
* useQuery({
* queryKey: api.queryKey,
* queryFn: () => fetch(api.url),
* });
* ```
*/
get queryKey() {
return this._key;
}
toString(): string {
return this._url.toString();
}
}