@hyper-fetch/orpc 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/README.md +100 -2
  2. package/__tests__/e2e/e2e.conformance.spec.ts +187 -0
  3. package/__tests__/e2e/e2e.orpc-server.ts +163 -0
  4. package/__tests__/e2e/e2e.orpc.spec.ts +338 -0
  5. package/__tests__/e2e/e2e.react.spec.tsx +219 -0
  6. package/__tests__/features/adapter/adapter.fetch.spec.ts +388 -0
  7. package/__tests__/features/adapter/adapter.lifecycle.spec.ts +529 -0
  8. package/__tests__/features/adapter/adapter.schema.spec.ts +271 -0
  9. package/__tests__/features/adapter/adapter.transport.spec.ts +346 -0
  10. package/__tests__/features/adapter/adapter.utils.spec.ts +329 -0
  11. package/__tests__/tsconfig.json +16 -0
  12. package/__tests__/vitest.setup.ts +5 -0
  13. package/dist/adapter/adapter.constants.d.ts +12 -0
  14. package/dist/adapter/adapter.constants.d.ts.map +1 -0
  15. package/dist/adapter/adapter.d.ts +10 -0
  16. package/dist/adapter/adapter.d.ts.map +1 -0
  17. package/dist/adapter/adapter.fetch.d.ts +3 -0
  18. package/dist/adapter/adapter.fetch.d.ts.map +1 -0
  19. package/dist/adapter/adapter.schema.d.ts +50 -0
  20. package/dist/adapter/adapter.schema.d.ts.map +1 -0
  21. package/dist/adapter/adapter.types.d.ts +42 -0
  22. package/dist/adapter/adapter.types.d.ts.map +1 -0
  23. package/dist/adapter/adapter.utils.d.ts +52 -0
  24. package/dist/adapter/adapter.utils.d.ts.map +1 -0
  25. package/dist/adapter/index.d.ts +7 -0
  26. package/dist/adapter/index.d.ts.map +1 -0
  27. package/dist/index.d.ts +2 -0
  28. package/dist/index.d.ts.map +1 -0
  29. package/dist/index.mjs +282 -0
  30. package/dist/index.mjs.map +1 -0
  31. package/package.json +74 -4
  32. package/project.json +4 -0
  33. package/src/adapter/adapter.constants.ts +20 -0
  34. package/src/adapter/adapter.fetch.ts +227 -0
  35. package/src/adapter/adapter.schema.ts +73 -0
  36. package/src/adapter/adapter.ts +13 -0
  37. package/src/adapter/adapter.types.ts +65 -0
  38. package/src/adapter/adapter.utils.ts +189 -0
  39. package/src/adapter/index.ts +6 -0
  40. package/src/index.ts +3 -0
  41. package/tsconfig.json +12 -0
  42. package/vite.config.ts +42 -0
@@ -0,0 +1,529 @@
1
+ /**
2
+ * @vitest-environment node
3
+ */
4
+ import type { RequestInstance } from "@hyper-fetch/core";
5
+ import { createClient, getErrorMessage } from "@hyper-fetch/core";
6
+ import { createHttpMockingServer } from "@hyper-fetch/testing";
7
+ import { delay, http, HttpResponse } from "msw";
8
+
9
+ import { OrpcAdapter, OrpcMethods, orpcExtra } from "../../../src/adapter";
10
+
11
+ const { server, startServer, stopServer, resetMocks } = createHttpMockingServer();
12
+
13
+ const url = "http://localhost:3000/rpc";
14
+
15
+ type User = { id: number; name: string };
16
+
17
+ const orpcError = { defined: false, code: "INTERNAL_SERVER_ERROR", status: 500, message: "Nope", data: undefined };
18
+
19
+ /** The input part of the serialized body */
20
+ const readInput = async (request: Request) =>
21
+ JSON.stringify(((await request.clone().json()) as { json: unknown }).json);
22
+
23
+ describe("Orpc Adapter [ Lifecycle ]", () => {
24
+ let client = createClient({ url, mode: "client" }).setAdapter(OrpcAdapter());
25
+
26
+ const createQuery = () =>
27
+ client.createRequest<{ response: User; payload: { id: number } }>()({ endpoint: "user/byId" });
28
+ const createMutation = () =>
29
+ client.createRequest<{ response: User; payload: { name: string } }>()({
30
+ endpoint: "user/create",
31
+ method: "MUTATION",
32
+ });
33
+
34
+ const respondWith = (data: unknown, procedure = "user/byId") => {
35
+ const calls: Request[] = [];
36
+ server.use(
37
+ http.post(`${url}/${procedure}`, ({ request }) => {
38
+ calls.push(request);
39
+ return HttpResponse.json({ json: data });
40
+ }),
41
+ );
42
+ return calls;
43
+ };
44
+
45
+ beforeAll(() => {
46
+ startServer();
47
+ });
48
+
49
+ beforeEach(() => {
50
+ client = createClient({ url, mode: "client" }).setAdapter(OrpcAdapter());
51
+ });
52
+
53
+ afterEach(() => {
54
+ resetMocks();
55
+ client.clear();
56
+ });
57
+
58
+ afterAll(() => {
59
+ stopServer();
60
+ });
61
+
62
+ describe("when creating the adapter", () => {
63
+ it("should expose the adapter defaults", () => {
64
+ const adapter = OrpcAdapter();
65
+
66
+ expect(adapter.name).toBe("orpc");
67
+ expect(adapter.defaultMethod).toBe(OrpcMethods.QUERY);
68
+ expect(adapter.defaultExtra).toStrictEqual(orpcExtra);
69
+ expect(adapter.systemErrorStatus).toBe(0);
70
+ expect(adapter.systemErrorExtra).toStrictEqual(orpcExtra);
71
+ });
72
+
73
+ it("should create independent adapters", () => {
74
+ expect(OrpcAdapter()).not.toBe(OrpcAdapter());
75
+ });
76
+
77
+ it("should map the endpoint for the devtools", () => {
78
+ expect(OrpcAdapter().unstable_devtoolsEndpointGetter("user/byId")).toBe("/user/byId");
79
+ });
80
+ });
81
+
82
+ describe("when using the interceptors", () => {
83
+ it("should send the headers added in onRequest", async () => {
84
+ const calls = respondWith({ id: 1, name: "John" });
85
+ client.onRequest((request) => request.setHeaders({ "x-tenant": "acme" }));
86
+
87
+ await createQuery().setPayload({ id: 1 }).send();
88
+
89
+ expect(calls[0].headers.get("x-tenant")).toBe("acme");
90
+ });
91
+
92
+ it("should send the headers added in onAuth", async () => {
93
+ const calls = respondWith({ id: 1, name: "John" });
94
+ client.onAuth((request) => request.setHeaders({ Authorization: "Bearer token" }));
95
+
96
+ await createQuery().setPayload({ id: 1 }).send();
97
+
98
+ expect(calls[0].headers.get("authorization")).toBe("Bearer token");
99
+ });
100
+
101
+ it("should skip onAuth for public requests", async () => {
102
+ const calls = respondWith({ id: 1, name: "John" });
103
+ client.onAuth((request) => request.setHeaders({ Authorization: "Bearer token" }));
104
+
105
+ await createQuery().setAuth(false).setPayload({ id: 1 }).send();
106
+
107
+ expect(calls[0].headers.get("authorization")).toBeNull();
108
+ });
109
+
110
+ it("should encode the input changed by the request mapper", async () => {
111
+ const calls = respondWith({ id: 2, name: "Jane" });
112
+
113
+ await createQuery()
114
+ .setPayload({ id: 1 })
115
+ .setRequestMapper((request) => request.setPayload({ id: 2 }))
116
+ .send();
117
+
118
+ expect(await readInput(calls[0])).toBe('{"id":2}');
119
+ });
120
+
121
+ it("should pass the mapped response to onSuccess", async () => {
122
+ respondWith({ id: 1, name: "John" });
123
+ const onSuccess = vi.fn((response) => response);
124
+ client.onSuccess(onSuccess);
125
+
126
+ await createQuery().setPayload({ id: 1 }).send();
127
+
128
+ expect(onSuccess.mock.calls[0][0]).toMatchObject({ data: { id: 1, name: "John" }, status: 200, success: true });
129
+ });
130
+
131
+ it("should pass the mapped error to onError", async () => {
132
+ server.use(http.post(`${url}/user/byId`, () => HttpResponse.json({ json: orpcError }, { status: 500 })));
133
+ const onError = vi.fn((response) => response);
134
+ client.onError(onError);
135
+
136
+ await createQuery().setPayload({ id: 1 }).send();
137
+
138
+ expect(onError.mock.calls[0][0]).toMatchObject({ error: orpcError, status: 500, success: false });
139
+ });
140
+
141
+ it("should let the response mapper change the result", async () => {
142
+ respondWith({ id: 1, name: "John" });
143
+
144
+ const response = await createQuery()
145
+ .setPayload({ id: 1 })
146
+ .setResponseMapper((res) => ({ ...res, data: { ...res.data, name: "Mapped" } }) as typeof res)
147
+ .send();
148
+
149
+ expect(response.data).toStrictEqual({ id: 1, name: "Mapped" });
150
+ });
151
+ });
152
+
153
+ describe("when following the request events", () => {
154
+ it("should trigger the events in order", async () => {
155
+ respondWith({ id: 1, name: "John" });
156
+ const events: string[] = [];
157
+
158
+ await createQuery()
159
+ .setPayload({ id: 1 })
160
+ .send({
161
+ onBeforeSent: () => events.push("beforeSent"),
162
+ onRequestStart: () => events.push("requestStart"),
163
+ onResponseStart: () => events.push("responseStart"),
164
+ onResponse: () => events.push("response"),
165
+ });
166
+
167
+ expect(events).toStrictEqual(["beforeSent", "requestStart", "responseStart", "response"]);
168
+ });
169
+
170
+ it("should report the upload progress with the size of the mutation body", async () => {
171
+ server.use(http.post(`${url}/user/create`, () => HttpResponse.json({ json: null })));
172
+ const onUploadProgress = vi.fn();
173
+ const payload = { name: "zażółć 🎡" };
174
+ const size = new Blob([JSON.stringify({ json: payload })]).size;
175
+
176
+ await createMutation().setPayload(payload).send({ onUploadProgress });
177
+
178
+ expect(onUploadProgress).toHaveBeenCalledWith(expect.objectContaining({ loaded: size, total: size }));
179
+ });
180
+ });
181
+
182
+ describe("when retrying", () => {
183
+ it("should retry a failed query until it succeeds", async () => {
184
+ let attempts = 0;
185
+ server.use(
186
+ http.post(`${url}/user/byId`, () => {
187
+ attempts += 1;
188
+ return attempts < 3
189
+ ? HttpResponse.json({ json: orpcError }, { status: 500 })
190
+ : HttpResponse.json({ json: { id: 1, name: "John" } });
191
+ }),
192
+ );
193
+
194
+ const response = await createQuery().setPayload({ id: 1 }).setRetry(2).setRetryTime(1).send();
195
+
196
+ expect(attempts).toBe(3);
197
+ expect(response.data).toStrictEqual({ id: 1, name: "John" });
198
+ });
199
+
200
+ it("should send the same input with every attempt", async () => {
201
+ const inputs: (string | null)[] = [];
202
+ server.use(
203
+ http.post(`${url}/user/byId`, async ({ request }) => {
204
+ inputs.push(await readInput(request));
205
+ return HttpResponse.json({ json: orpcError }, { status: 500 });
206
+ }),
207
+ );
208
+
209
+ await createQuery().setPayload({ id: 7 }).setRetry(2).setRetryTime(1).send();
210
+
211
+ expect(inputs).toStrictEqual(['{"id":7}', '{"id":7}', '{"id":7}']);
212
+ });
213
+
214
+ it("should retry a failed mutation with the same body", async () => {
215
+ const bodies: string[] = [];
216
+ server.use(
217
+ http.post(`${url}/user/create`, async ({ request }) => {
218
+ bodies.push(await request.text());
219
+ return bodies.length < 2
220
+ ? HttpResponse.json({ json: orpcError }, { status: 500 })
221
+ : HttpResponse.json({ json: { id: 3, name: "Jack" } });
222
+ }),
223
+ );
224
+
225
+ const response = await createMutation().setPayload({ name: "Jack" }).setRetry(1).setRetryTime(1).send();
226
+
227
+ expect(bodies).toStrictEqual(['{"json":{"name":"Jack"}}', '{"json":{"name":"Jack"}}']);
228
+ expect(response.data).toStrictEqual({ id: 3, name: "Jack" });
229
+ });
230
+
231
+ it("should stop retrying based on the oRPC error", async () => {
232
+ let attempts = 0;
233
+ const notFound = { defined: true, code: "NOT_FOUND", status: 404, message: "Nope", data: undefined };
234
+ server.use(
235
+ http.post(`${url}/user/byId`, () => {
236
+ attempts += 1;
237
+ return HttpResponse.json({ json: notFound }, { status: 404 });
238
+ }),
239
+ );
240
+
241
+ const response = await createQuery()
242
+ .setPayload({ id: 1 })
243
+ .setRetry(5)
244
+ .setRetryTime(1)
245
+ .setRetryOnError(({ error }) => (error as typeof notFound | null)?.code !== "NOT_FOUND")
246
+ .send();
247
+
248
+ expect(attempts).toBe(1);
249
+ expect(response.status).toBe(404);
250
+ });
251
+ });
252
+
253
+ describe("when requests run at the same time", () => {
254
+ it("should cancel the running call with the same input", async () => {
255
+ let calls = 0;
256
+ server.use(
257
+ http.post(`${url}/user/byId`, async () => {
258
+ calls += 1;
259
+ if (calls === 1) {
260
+ await delay("infinite");
261
+ }
262
+ return HttpResponse.json({ json: { id: 1, name: "John" } });
263
+ }),
264
+ );
265
+ const request = createQuery().setCancelable(true).setDeduplicate(false).setPayload({ id: 1 });
266
+
267
+ const pending = request.send();
268
+ await vi.waitFor(() => expect(calls).toBe(1));
269
+ const second = await request.send();
270
+ const first = await pending;
271
+
272
+ expect(first.error).toStrictEqual(getErrorMessage("abort"));
273
+ expect(second.data).toStrictEqual({ id: 1, name: "John" });
274
+ });
275
+
276
+ it("should keep the running calls with a different input", async () => {
277
+ respondWith({ id: 1, name: "John" });
278
+ const request = createQuery().setCancelable(true);
279
+
280
+ const [first, second] = await Promise.all([
281
+ request.setPayload({ id: 1 }).send(),
282
+ request.setPayload({ id: 2 }).send(),
283
+ ]);
284
+
285
+ expect(first.success).toBe(true);
286
+ expect(second.success).toBe(true);
287
+ });
288
+
289
+ it("should cancel a different input when the calls share the query key", async () => {
290
+ server.use(
291
+ http.post(`${url}/user/byId`, async ({ request }) => {
292
+ if ((await readInput(request)) === '{"id":1}') {
293
+ await delay("infinite");
294
+ }
295
+ return HttpResponse.json({ json: { id: 2, name: "Jane" } });
296
+ }),
297
+ );
298
+ const request = createQuery().setCancelable(true).setDeduplicate(false).setQueryKey("user-search");
299
+
300
+ const [first, second] = await Promise.all([
301
+ request.setPayload({ id: 1 }).send(),
302
+ request.setPayload({ id: 2 }).send(),
303
+ ]);
304
+
305
+ expect(first.error).toStrictEqual(getErrorMessage("abort"));
306
+ expect(second.data).toStrictEqual({ id: 2, name: "Jane" });
307
+ });
308
+
309
+ it("should abort every running call of the procedure", async () => {
310
+ const started: (string | null)[] = [];
311
+ server.use(
312
+ http.post(`${url}/user/byId`, async ({ request }) => {
313
+ started.push(await readInput(request));
314
+ await delay("infinite");
315
+ return HttpResponse.json({ json: null });
316
+ }),
317
+ );
318
+ const request = createQuery();
319
+
320
+ const pending = Promise.all([request.setPayload({ id: 1 }).send(), request.setPayload({ id: 2 }).send()]);
321
+ await vi.waitFor(() => expect(started).toHaveLength(2));
322
+ request.abort();
323
+ const responses = await pending;
324
+
325
+ expect(responses.map(({ error }) => error)).toStrictEqual([getErrorMessage("abort"), getErrorMessage("abort")]);
326
+ });
327
+
328
+ it("should not cancel a different procedure", async () => {
329
+ respondWith({ id: 1, name: "John" });
330
+ respondWith([{ id: 1, name: "John" }], "user/list");
331
+
332
+ const [byId, list] = await Promise.all([
333
+ createQuery().setCancelable(true).setPayload({ id: 1 }).send(),
334
+ client.createRequest<{ response: User[] }>()({ endpoint: "user/list", cancelable: true }).send(),
335
+ ]);
336
+
337
+ expect(byId.success).toBe(true);
338
+ expect(list.success).toBe(true);
339
+ });
340
+
341
+ it("should send every call when deduplication is turned off", async () => {
342
+ const calls = respondWith({ id: 1, name: "John" });
343
+ const request = createQuery().setDeduplicate(false).setPayload({ id: 1 });
344
+
345
+ await Promise.all([request.send(), request.send()]);
346
+
347
+ expect(calls).toHaveLength(2);
348
+ });
349
+
350
+ it("should not deduplicate mutations", async () => {
351
+ let calls = 0;
352
+ server.use(
353
+ http.post(`${url}/user/create`, () => {
354
+ calls += 1;
355
+ return HttpResponse.json({ json: { id: calls, name: "Jack" } });
356
+ }),
357
+ );
358
+ const request = createMutation().setPayload({ name: "Jack" });
359
+
360
+ await Promise.all([request.send(), request.send()]);
361
+
362
+ expect(calls).toBe(2);
363
+ });
364
+
365
+ it("should run queued mutations one by one", async () => {
366
+ let running = 0;
367
+ let maxRunning = 0;
368
+ const order: string[] = [];
369
+ server.use(
370
+ http.post(`${url}/user/create`, async ({ request }) => {
371
+ running += 1;
372
+ maxRunning = Math.max(maxRunning, running);
373
+ const { name } = ((await request.json()) as { json: { name: string } }).json;
374
+ order.push(name);
375
+ await delay(1);
376
+ running -= 1;
377
+ return HttpResponse.json({ json: { id: 1, name } });
378
+ }),
379
+ );
380
+ const request = createMutation().setQueued(true).setQueryKey("create-users");
381
+
382
+ await Promise.all([
383
+ request.setPayload({ name: "first" }).send(),
384
+ request.setPayload({ name: "second" }).send(),
385
+ request.setPayload({ name: "third" }).send(),
386
+ ]);
387
+
388
+ expect(maxRunning).toBe(1);
389
+ expect(order).toStrictEqual(["first", "second", "third"]);
390
+ });
391
+
392
+ it("should run queued calls with different inputs independently", async () => {
393
+ const started: (string | null)[] = [];
394
+ let release = () => {};
395
+ const released = new Promise<void>((resolve) => {
396
+ release = resolve;
397
+ });
398
+ server.use(
399
+ http.post(`${url}/user/byId`, async ({ request }) => {
400
+ started.push(await readInput(request));
401
+ await released;
402
+ return HttpResponse.json({ json: { id: 1, name: "John" } });
403
+ }),
404
+ );
405
+ const request = createQuery().setQueued(true);
406
+
407
+ const pending = Promise.all([request.setPayload({ id: 1 }).send(), request.setPayload({ id: 2 }).send()]);
408
+ await vi.waitFor(() => expect(started).toHaveLength(2));
409
+ release();
410
+ await pending;
411
+
412
+ expect(started).toIncludeSameMembers(['{"id":1}', '{"id":2}']);
413
+ });
414
+ });
415
+
416
+ describe("when using the cache", () => {
417
+ it("should store the data with the extra", async () => {
418
+ respondWith({ id: 1, name: "John" });
419
+ const request = createQuery().setPayload({ id: 1 });
420
+
421
+ await request.send();
422
+
423
+ expect(client.cache.get(request.cacheKey)).toMatchObject({
424
+ data: { id: 1, name: "John" },
425
+ status: 200,
426
+ success: true,
427
+ });
428
+ });
429
+
430
+ it("should not store the failed responses", async () => {
431
+ server.use(http.post(`${url}/user/byId`, () => HttpResponse.json({ json: orpcError }, { status: 500 })));
432
+ const request = createQuery().setPayload({ id: 1 });
433
+
434
+ await request.send();
435
+
436
+ expect(client.cache.get(request.cacheKey)).toBeUndefined();
437
+ });
438
+
439
+ it("should not store the response when the cache is turned off", async () => {
440
+ respondWith({ id: 1, name: "John" });
441
+ const request = createQuery().setCache(false).setPayload({ id: 1 });
442
+
443
+ await request.send();
444
+
445
+ expect(client.cache.get(request.cacheKey)).toBeUndefined();
446
+ });
447
+
448
+ it("should change the keys together with the input", () => {
449
+ const request = createQuery();
450
+ const withInput = request.setPayload({ id: 1 });
451
+
452
+ expect(withInput.cacheKey).not.toBe(request.cacheKey);
453
+ expect(withInput.setPayload({ id: 1 }).cacheKey).toBe(withInput.cacheKey);
454
+ });
455
+
456
+ it("should keep custom keys", () => {
457
+ const request = createQuery().setCacheKey("custom-cache").setQueryKey("custom-query").setAbortKey("custom-abort");
458
+ const withInput = request.setPayload({ id: 1 });
459
+
460
+ expect(withInput.cacheKey).toBe("custom-cache");
461
+ expect(withInput.queryKey).toBe("custom-query");
462
+ expect(withInput.abortKey).toBe("custom-abort");
463
+ });
464
+
465
+ it("should use separate abort keys for cancelable requests", () => {
466
+ expect(createQuery().setCancelable(true).abortKey).not.toBe(createQuery().abortKey);
467
+ });
468
+
469
+ it("should isolate the scopes", async () => {
470
+ respondWith({ id: 1, name: "John" });
471
+ const first = createQuery().setPayload({ id: 1 }).setScope("first");
472
+ const second = createQuery().setPayload({ id: 1 }).setScope("second");
473
+
474
+ await first.send();
475
+
476
+ expect(client.cache.get(`first__${first.cacheKey}`)).toMatchObject({ data: { id: 1, name: "John" } });
477
+ expect(client.cache.get(`second__${second.cacheKey}`)).toBeUndefined();
478
+ });
479
+ });
480
+
481
+ describe("when restoring the requests", () => {
482
+ it("should recreate a query from JSON", async () => {
483
+ const calls = respondWith({ id: 1, name: "John" });
484
+ const request = createQuery().setPayload({ id: 1 });
485
+
486
+ const restored = client.fromJSON<{ response: User; payload: { id: number } }>(request.toJSON());
487
+ const response = await (restored as RequestInstance).send();
488
+
489
+ expect(restored.method).toBe("QUERY");
490
+ expect(restored.cacheKey).toBe(request.cacheKey);
491
+ expect(restored.queryKey).toBe(request.queryKey);
492
+ expect(restored.abortKey).toBe(request.abortKey);
493
+ expect(await readInput(calls[0])).toBe('{"id":1}');
494
+ expect(response.data).toStrictEqual({ id: 1, name: "John" });
495
+ });
496
+
497
+ it("should recreate a mutation from JSON", async () => {
498
+ let body = "";
499
+ server.use(
500
+ http.post(`${url}/user/create`, async ({ request }) => {
501
+ body = await request.text();
502
+ return HttpResponse.json({ json: { id: 3, name: "Jack" } });
503
+ }),
504
+ );
505
+ const request = createMutation().setPayload({ name: "Jack" });
506
+
507
+ const restored = client.fromJSON<{ response: User; payload: { name: string } }>(request.toJSON());
508
+ await (restored as RequestInstance).send();
509
+
510
+ expect(restored.method).toBe("MUTATION");
511
+ expect(body).toBe('{"json":{"name":"Jack"}}');
512
+ });
513
+ });
514
+
515
+ describe("when mocking the requests", () => {
516
+ it("should skip the network", async () => {
517
+ const spy = vi.spyOn(globalThis, "fetch");
518
+
519
+ const response = await createQuery()
520
+ .setPayload({ id: 1 })
521
+ .setMock(() => ({ data: { id: 9, name: "Mock" }, status: 200 }))
522
+ .send();
523
+
524
+ expect(response.data).toStrictEqual({ id: 9, name: "Mock" });
525
+ expect(spy).not.toHaveBeenCalled();
526
+ spy.mockRestore();
527
+ });
528
+ });
529
+ });