-
-
Notifications
You must be signed in to change notification settings - Fork 92
/
endpoint.ts
576 lines (514 loc) · 17.4 KB
/
endpoint.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
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
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
import nock from 'nock';
import { Schema, Entity } from '@rest-hooks/normalizr';
import { camelCase, snakeCase } from 'lodash';
import Endpoint, { EndpointOptions, Make } from '../endpoint';
import { EndpointInterface } from '../interface';
describe('Endpoint', () => {
const payload = { id: '5', username: 'bobber' };
const payload2 = { id: '6', username: 'tomm' };
const assetPayload = { symbol: 'btc', price: '5.0' };
const fetchUsers = ({ id }: { id: string }) =>
fetch(`/users/${id}`).then(res => res.json()) as Promise<typeof payload>;
const fetchAsset = ({ symbol }: { symbol: string }) =>
fetch(`/asset/${symbol}`).then(res => res.json()) as Promise<
typeof assetPayload
>;
beforeAll(() => {
nock(/.*/)
.persist()
.defaultReplyHeaders({
'Access-Control-Allow-Origin': '*',
'Content-Type': 'application/json',
})
.options(/.*/)
.reply(200)
.get(`/users/${payload.id}`)
.reply(200, payload)
.get(`/asset/${assetPayload.symbol}`)
.reply(200, assetPayload);
nock(/.*/, { reqheaders: { Auth: 'password' } })
.persist()
.defaultReplyHeaders({
'Access-Control-Allow-Origin': '*',
'Content-Type': 'application/json',
})
.options(/.*/)
.reply(200)
.get(`/users/current`)
.reply(200, payload);
nock(/.*/, { reqheaders: { Auth: 'password2' } })
.persist()
.defaultReplyHeaders({
'Access-Control-Allow-Origin': '*',
'Content-Type': 'application/json',
})
.options(/.*/)
.reply(200)
.get(`/users/current`)
.reply(200, payload2);
});
afterAll(() => {
nock.cleanAll();
});
describe('Function', () => {
it('should work when called as function', async () => {
const UserDetail = new Endpoint(fetchUsers);
// check return type and call params
const response = await UserDetail({ id: payload.id });
expect(response).toEqual(payload);
expect(response.username).toBe(payload.username);
// @ts-expect-error
expect(response.notexist).toBeUndefined();
// check additional properties defaults
expect(UserDetail.sideEffect).toBe(undefined);
//expect(UserDetail.schema).toBeUndefined(); TODO: re-enable once we don't care about FetchShape compatibility
expect(UserDetail.key({ id: payload.id })).toMatchInlineSnapshot(
`"fetchUsers {\\"id\\":\\"5\\"}"`,
);
// @ts-expect-error
expect(UserDetail.notexist).toBeUndefined();
// @ts-expect-error
const a: 'mutate' = UserDetail.type;
// these are all meant to fail - are typescript tests
expect(() => {
// @ts-expect-error
UserDetail({ id: 5 });
// @ts-expect-error
UserDetail();
}).toThrow();
});
});
it('should work when extended', async () => {
const BaseFetch = new Endpoint(fetchUsers);
// @ts-expect-error
const aa: true = BaseFetch.sideEffect;
const bb: undefined = BaseFetch.sideEffect;
const UserDetail = new Endpoint(fetchUsers).extend({
sideEffect: true,
key: ({ id }: { id: string }) => `fetch my user ${id}`,
});
// @ts-expect-error
const a: undefined = UserDetail.sideEffect;
const b: true = UserDetail.sideEffect;
// ts-expect-error
//const c: undefined = UserDetail.extend({ dataExpiryLength: 5 }).sideEffect;
//const d: true = UserDetail.extend({ dataExpiryLength: 5 }).sideEffect;
function t(a: EndpointInterface<typeof fetchUsers, any, undefined>) {}
// @ts-expect-error
t(UserDetail);
t(BaseFetch);
expect(UserDetail.key({ id: '500' })).toMatchInlineSnapshot(
`"fetch my user 500"`,
);
// @ts-expect-error
expect(() => UserDetail.key()).toThrow();
// @ts-expect-error
expect(UserDetail.key({ not: 'five' })).toMatchInlineSnapshot(
`"fetch my user undefined"`,
);
// @ts-expect-error
expect(UserDetail.key({ id: 5 })).toMatchInlineSnapshot(
`"fetch my user 5"`,
);
new Endpoint(fetchUsers).extend({
sideEffect: true,
// @ts-expect-error
key: ({ a }: { a: number }) => `fetch my user ${a}`,
});
new Endpoint(fetchUsers).extend({
sideEffect: true,
fetch: fetchAsset,
// TODO: ts-expect-error
key: ({ id }: { id: string }) => `fetch my user ${id}`,
});
const AssetDetail = new Endpoint(fetchUsers).extend({
fetch: fetchAsset,
});
const response = await AssetDetail({ symbol: assetPayload.symbol });
expect(response).toEqual(assetPayload);
expect(response.price).toBe(assetPayload.price);
// @ts-expect-error
expect(response.notexist).toBeUndefined();
expect(AssetDetail.key({ symbol: 'doge' })).toMatchInlineSnapshot(
`"fetchAsset {\\"symbol\\":\\"doge\\"}"`,
);
});
it('should infer return type when schema is specified but fetch function has no typing', async () => {
class User extends Entity {
readonly id: string = '';
readonly username: string = '';
pk() {
return this.id;
}
}
class User2 extends User {
readonly extra: number = 0;
}
const UserDetail = new Endpoint(
({ id }: { id: string }) => fetch(`/users/${id}`).then(res => res.json()),
{ schema: User },
);
const user = await UserDetail({ id: payload.id });
expect(user).toEqual(payload);
expect(user.username).toBe(payload.username);
// extends
const Extended = UserDetail.extend({
schema: User2,
});
const user2 = await Extended({ id: payload.id });
expect(user2).toEqual(payload);
// doesn't actually generate class
expect(user2.extra).toBe(undefined);
});
describe('auth patterns (usage with `this`)', () => {
function fetchAuthd(this: { token: string }): Promise<typeof payload> {
return fetch(`/users/current`, {
headers: { Auth: this.token },
}).then(res => res.json());
}
function key(this: { token: string }) {
return `current user ${this.token}`;
}
it('makes', async () => {
const UserCurrent = new Endpoint(fetchAuthd, { token: 'password', key });
const response = await UserCurrent();
expect(response).toEqual(payload);
expect(response.username).toBe(payload.username);
expect(UserCurrent.key()).toMatchInlineSnapshot(
`"current user password"`,
);
UserCurrent.key = function () {
return Object.getPrototypeOf(UserCurrent).key.call(this) + 'never';
};
});
it('should use provided context in fetch and key', async () => {
const UserCurrent = new Endpoint(fetchAuthd, { token: 'password', key });
const response = await UserCurrent();
expect(response).toEqual(payload);
expect(response.username).toBe(payload.username);
// @ts-expect-error
expect(response.notexist).toBeUndefined();
expect(UserCurrent.key()).toMatchInlineSnapshot(
`"current user password"`,
);
});
it('should typescript error when missing expected this members', () => {
// @ts-expect-error
new Endpoint(fetchAuthd, { key });
// @ts-expect-error
new Endpoint(fetchAuthd, { token: 5, key });
});
function key2(this: { token: number }) {
return `current user ${this.token}`;
}
function key3(this: { token: string }, { id }: { id: string }) {
return `current user ${this.token}`;
}
function key4() {
return `current user`;
}
it('should not allow mismatched key', () => {
// TODO: ts-expect-error new Endpoint(fetchAuthd, { token: 'hi', key: key2 });
// @ts-expect-error
new Endpoint(fetchAuthd, { token: 'hi', key: key3 });
new Endpoint(fetchAuthd, { token: 'hi', key: key4 });
});
it('should not allow mismatched key when extending', () => {
const UserCurrent = new Endpoint(fetchAuthd, { token: 'password', key });
// TODO: ts-expect-error UserCurrent.extend({ key: key2 });
// @ts-expect-error
UserCurrent.extend({ key: key3 });
const a = UserCurrent.extend({ key: key4 });
expect(a.key()).toBe(key4());
});
it('should break when trying to use reserved `this` members', () => {
function fetchAuthd(this: {
token: string;
sideEffect: number;
}): Promise<typeof payload> {
return fetch(`/users/current`, {
headers: { Auth: this.token },
}).then(res => res.json());
}
// @ts-expect-error TODO: make this error message actually readable
new Endpoint(fetchAuthd, {
token: 'password',
key,
sideEffect: 5,
});
});
});
describe('helper members', () => {
it('url helper', async () => {
const url = ({ id }: { id: string }) => `/users/${id}`;
const fetchUsers = function (
this: { url: (params: { id: string }) => string },
{ id }: { id: string },
) {
return fetch(this.url({ id })).then(res => res.json()) as Promise<
typeof payload
>;
};
// @ts-expect-error
new Endpoint(fetchUsers, { url: '', random: 5 });
// @ts-expect-error
new Endpoint(fetchUsers, { url }).extend({ url: 'hi' });
const UserDetail = new Endpoint(
function ({ id }: { id: string }) {
this.random;
// @ts-expect-error
this.notexistant;
return fetch(this.url({ id })).then(res => res.json()) as Promise<
typeof payload
>;
},
{
url,
random: 599,
dataExpiryLength: 5000,
},
);
const a: undefined = UserDetail.sideEffect;
// @ts-expect-error
const b: true = UserDetail.sideEffect;
UserDetail.schema;
UserDetail.random;
// @ts-expect-error
UserDetail.nonexistant;
UserDetail.key({ id: 'hi' });
// @ts-expect-error
() => UserDetail.key({ nonexistant: 5 });
// @ts-expect-error
() => UserDetail.key({ id: 5 });
let res = await UserDetail({ id: payload.id });
expect(res).toEqual(payload);
expect(res.username).toBe(payload.username);
// @ts-expect-error
expect(res.notexist).toBeUndefined();
// test extending parts that aren't used in this
const Extended = UserDetail.extend({ random: 100 });
res = await Extended({ id: payload.id });
expect(res).toEqual(payload);
expect(res.username).toBe(payload.username);
// @ts-expect-error
expect(res.notexist).toBeUndefined();
UserDetail.extend({
url: function (params: { id: string }) {
return this.constructor.prototype.url(params) + '/more';
},
// @ts-expect-error
random: '600',
});
const Test = UserDetail.extend({
random: 600,
});
// check return type and call params
const response = await Test({ id: payload.id });
expect(response).toEqual(payload);
expect(response.username).toBe(payload.username);
// @ts-expect-error
expect(response.notexist).toBeUndefined();
});
it('should work with key', () => {
const url = ({ id }: { id: string }) => `/users/${id}`;
class User extends Entity {
readonly id: string = '';
pk() {
return this.id;
}
}
const UserDetail = new Endpoint(
function ({ id }: { id: string }) {
this.schema;
this.random;
// @ts-expect-error
this.notexistant;
return fetch(this.url({ id })).then(res => res.json()) as Promise<
typeof payload
>;
},
{
url,
random: 599,
schema: [User],
key: function (this: any, { id }: { id: string }) {
this.random;
this.schema;
return id + 'hi';
},
},
);
const sch: typeof User[] = UserDetail.schema;
const s: undefined = UserDetail.sideEffect;
UserDetail.random;
// @ts-expect-error
UserDetail.nonexistant;
UserDetail.key({ id: 'hi' });
// @ts-expect-error
() => UserDetail.key({ nonexistant: 5 });
// @ts-expect-error
() => UserDetail.key({ id: 5 });
});
});
describe('AbortController', () => {
const url = ({ id }: { id: string }) => `/users/${id}`;
const UserDetail = new Endpoint(
function ({ id }: { id: string }) {
const init: RequestInit = {};
if (this.signal) {
init.signal = this.signal;
}
return fetch(this.url({ id }), init).then(res => res.json()) as Promise<
typeof payload
>;
},
{
url,
signal: undefined as AbortSignal | undefined,
},
);
it('should work without signal', async () => {
const user = await UserDetail({ id: payload.id });
expect(user.username).toBe(payload.username);
});
it('should reject when aborted', async () => {
const abort = new AbortController();
const AbortUser = UserDetail.extend({ signal: abort.signal });
await expect(async () => {
const promise = AbortUser({ id: payload.id });
abort.abort();
return await promise;
}).rejects.toMatchInlineSnapshot(`[AbortError: Aborted]`);
});
});
describe('class', () => {
/*class ResourceEndpoint<
F extends (params?: any, body?: any) => Promise<any>,
S extends Schema | undefined = undefined,
M extends true | undefined = undefined
> extends Endpoint<F, S, M> {
constructor(
fetchFunction: F,
options?: EndpointOptions<
(this: ThisParameterType<F>, ...args: Parameters<F>) => string,
S,
M
> &
ThisParameterType<F>,
) {
super(fetchFunction, options);
}
fetch(...args: Parameters<F>) {
return fetch(this.url(args[0]), this.init).then(res => res.json());
}
init: RequestInit = { method: 'GET' };
key(params: { id: string }) {
return `${this.init.method} ${this.url(params)}`;
}
}
const init = this.getFetchInit({ method: 'GET' });
const fetch = this.fetch.bind(this);
return new Endpoint(
function (
this: { url: (p: any) => string; init: RequestInit },
params: Readonly<object>,
) {
return fetch(this.url(params), this.init);
},
{
...this.getEndpointExtra(),
key: function (
this: { url: (p: any) => string; init: RequestInit },
params: Readonly<object>,
) {
return `${this.init.method} ${this.url(params)}`;
},
url: this.url.bind(this),
init,
},
);*/
/* describe('auth patterns', () => {
class AuthEndpoint<
F extends (
this: AuthEndpoint<any, any, any>,
params?: any,
body?: any,
) => Promise<any>,
S extends Schema | undefined = undefined,
M extends true | undefined = undefined
> extends Endpoint<F, S, M> {
token = 'password';
authdFetch(info: RequestInfo, init?: RequestInit) {
return fetch(info, {
...init,
headers: { ...init?.headers, Auth: this.token },
});
}
}
function fetchAuthd(
this: AuthEndpoint<any, any, any>,
): Promise<typeof payload> {
return this.authdFetch(`/users/current`).then(res => res.json());
}
it('should use provided context', async () => {
const UserCurrent = new AuthEndpoint(fetchAuthd);
const response = await UserCurrent();
expect(response).toEqual(payload);
expect(response.username).toBe(payload.username);
// @ts-expect-error
expect(response.notexist).toBeUndefined();
expect(UserCurrent.key()).toMatchInlineSnapshot(
`"fetchAuthd undefined"`,
);
});
it('should use extended token', async () => {
//sdf @ts-expect-error
const UserCurrent = new AuthEndpoint(fetchAuthd, {
token: 'password3',
}).extend({
token: 'password2',
sideEffect: true,
});
console.log((UserCurrent as any).token);
const response = await UserCurrent();
expect(response).toEqual(payload2);
expect(response.username).toBe(payload2.username);
// @ts-expect-error
expect(response.notexist).toBeUndefined();
expect(UserCurrent.key()).toMatchInlineSnapshot(
`"fetchAuthd undefined"`,
);
});
});
});*/
/*describe('custom fetch for snakeCase', () => {
function deeplyApplyKeyTransform(
obj: any,
transform: (key: string) => string,
) {
const ret: Record<string, any> = Array.isArray(obj) ? [] : {};
Object.keys(obj).forEach(key => {
if (obj[key] != null && typeof obj[key] === 'object') {
ret[transform(key)] = deeplyApplyKeyTransform(obj[key], transform);
} else {
ret[transform(key)] = obj[key];
}
});
return ret;
}
async function fetch(input: RequestInfo, init: RequestInit) {
// we'll need to do the inverse operation when sending data back to the server
if (init.body) {
init.body = deeplyApplyKeyTransform(init.body, snakeCase) as any;
}
// perform actual network request getting back json
const jsonResponse: object = await fetch(input, init);
// do the conversion!
return deeplyApplyKeyTransform(jsonResponse, camelCase);
}
const BaseEndpoint = new Endpoint(fetch);
it('should extends', () => {
BaseEndpoint.extend({ fetch: })
})*/
});
});