@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.
- package/README.md +100 -2
- package/__tests__/e2e/e2e.conformance.spec.ts +187 -0
- package/__tests__/e2e/e2e.orpc-server.ts +163 -0
- package/__tests__/e2e/e2e.orpc.spec.ts +338 -0
- package/__tests__/e2e/e2e.react.spec.tsx +219 -0
- package/__tests__/features/adapter/adapter.fetch.spec.ts +388 -0
- package/__tests__/features/adapter/adapter.lifecycle.spec.ts +529 -0
- package/__tests__/features/adapter/adapter.schema.spec.ts +271 -0
- package/__tests__/features/adapter/adapter.transport.spec.ts +346 -0
- package/__tests__/features/adapter/adapter.utils.spec.ts +329 -0
- package/__tests__/tsconfig.json +16 -0
- package/__tests__/vitest.setup.ts +5 -0
- package/dist/adapter/adapter.constants.d.ts +12 -0
- package/dist/adapter/adapter.constants.d.ts.map +1 -0
- package/dist/adapter/adapter.d.ts +10 -0
- package/dist/adapter/adapter.d.ts.map +1 -0
- package/dist/adapter/adapter.fetch.d.ts +3 -0
- package/dist/adapter/adapter.fetch.d.ts.map +1 -0
- package/dist/adapter/adapter.schema.d.ts +50 -0
- package/dist/adapter/adapter.schema.d.ts.map +1 -0
- package/dist/adapter/adapter.types.d.ts +42 -0
- package/dist/adapter/adapter.types.d.ts.map +1 -0
- package/dist/adapter/adapter.utils.d.ts +52 -0
- package/dist/adapter/adapter.utils.d.ts.map +1 -0
- package/dist/adapter/index.d.ts +7 -0
- package/dist/adapter/index.d.ts.map +1 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.mjs +282 -0
- package/dist/index.mjs.map +1 -0
- package/package.json +74 -4
- package/project.json +4 -0
- package/src/adapter/adapter.constants.ts +20 -0
- package/src/adapter/adapter.fetch.ts +227 -0
- package/src/adapter/adapter.schema.ts +73 -0
- package/src/adapter/adapter.ts +13 -0
- package/src/adapter/adapter.types.ts +65 -0
- package/src/adapter/adapter.utils.ts +189 -0
- package/src/adapter/index.ts +6 -0
- package/src/index.ts +3 -0
- package/tsconfig.json +12 -0
- package/vite.config.ts +42 -0
|
@@ -0,0 +1,388 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @vitest-environment node
|
|
3
|
+
*/
|
|
4
|
+
import { createClient, getErrorMessage, getRequestDispatcher } from "@hyper-fetch/core";
|
|
5
|
+
import { createHttpMockingServer } from "@hyper-fetch/testing";
|
|
6
|
+
import { http, HttpResponse } from "msw";
|
|
7
|
+
|
|
8
|
+
import type { OrpcAdapterOptionsType } from "../../../src/adapter";
|
|
9
|
+
import { OrpcAdapter } 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 notFound = { defined: true, code: "NOT_FOUND", status: 404, message: "User not found", data: { id: 1 } };
|
|
18
|
+
|
|
19
|
+
/** Money is sent as a `[currency, cents]` pair */
|
|
20
|
+
class Money {
|
|
21
|
+
constructor(
|
|
22
|
+
public currency: string,
|
|
23
|
+
public cents: number,
|
|
24
|
+
) {}
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
const moneySerializer: NonNullable<OrpcAdapterOptionsType["customJsonSerializers"]>[number] = {
|
|
28
|
+
type: 21,
|
|
29
|
+
condition: (value) => value instanceof Money,
|
|
30
|
+
serialize: (value: Money) => [value.currency, value.cents],
|
|
31
|
+
deserialize: ([currency, cents]: [string, number]) => new Money(currency, cents),
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
describe("Orpc Adapter [ Fetch ]", () => {
|
|
35
|
+
let client = createClient({ url }).setAdapter(OrpcAdapter());
|
|
36
|
+
|
|
37
|
+
const createQuery = () =>
|
|
38
|
+
client.createRequest<{ response: User; payload: { id: number } }>()({ endpoint: "user/byId", method: "QUERY" });
|
|
39
|
+
const createMutation = () =>
|
|
40
|
+
client.createRequest<{ response: User; payload: { name: string } }>()({
|
|
41
|
+
endpoint: "user/create",
|
|
42
|
+
method: "MUTATION",
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
/** Captures the request that reached the network */
|
|
46
|
+
const captureRequest = (method: "get" | "post", procedure: string, body?: unknown) => {
|
|
47
|
+
const captured: { current: Request | null; body: string; form: FormData | null } = {
|
|
48
|
+
current: null,
|
|
49
|
+
body: "",
|
|
50
|
+
form: null,
|
|
51
|
+
};
|
|
52
|
+
|
|
53
|
+
server.use(
|
|
54
|
+
http[method](`${url}/${procedure}`, async ({ request }) => {
|
|
55
|
+
captured.current = request.clone();
|
|
56
|
+
if (request.headers.get("content-type")?.startsWith("multipart/form-data")) {
|
|
57
|
+
captured.form = await request.formData();
|
|
58
|
+
} else {
|
|
59
|
+
captured.body = await request.text();
|
|
60
|
+
}
|
|
61
|
+
return HttpResponse.json((body ?? { json: null }) as Record<string, unknown>);
|
|
62
|
+
}),
|
|
63
|
+
);
|
|
64
|
+
|
|
65
|
+
return captured;
|
|
66
|
+
};
|
|
67
|
+
|
|
68
|
+
beforeAll(() => {
|
|
69
|
+
startServer();
|
|
70
|
+
});
|
|
71
|
+
|
|
72
|
+
beforeEach(() => {
|
|
73
|
+
client = createClient({ url }).setAdapter(OrpcAdapter());
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
afterEach(() => {
|
|
77
|
+
resetMocks();
|
|
78
|
+
client.clear();
|
|
79
|
+
});
|
|
80
|
+
|
|
81
|
+
afterAll(() => {
|
|
82
|
+
stopServer();
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
describe("when sending a query", () => {
|
|
86
|
+
it("should use QUERY as the default method", () => {
|
|
87
|
+
expect(client.createRequest()({ endpoint: "health" }).method).toBe("QUERY");
|
|
88
|
+
});
|
|
89
|
+
|
|
90
|
+
it("should use the fetch dispatcher and deduplicate by default", () => {
|
|
91
|
+
const request = createQuery();
|
|
92
|
+
|
|
93
|
+
expect(getRequestDispatcher(request)[1]).toBe(true);
|
|
94
|
+
expect(request.deduplicate).toBe(true);
|
|
95
|
+
});
|
|
96
|
+
|
|
97
|
+
it("should send a POST request with the serialized input by default", async () => {
|
|
98
|
+
const captured = captureRequest("post", "user/byId");
|
|
99
|
+
|
|
100
|
+
await createQuery().setPayload({ id: 1 }).send();
|
|
101
|
+
|
|
102
|
+
expect(captured.current?.method).toBe("POST");
|
|
103
|
+
expect(captured.current?.url).toBe(`${url}/user/byId`);
|
|
104
|
+
expect(captured.current?.headers.get("content-type")).toBe("application/json");
|
|
105
|
+
expect(captured.body).toBe('{"json":{"id":1}}');
|
|
106
|
+
});
|
|
107
|
+
|
|
108
|
+
it("should map the output to the response", async () => {
|
|
109
|
+
const user = { id: 1, name: "John" };
|
|
110
|
+
captureRequest("post", "user/byId", { json: user });
|
|
111
|
+
|
|
112
|
+
const response = await createQuery().setPayload({ id: 1 }).send();
|
|
113
|
+
|
|
114
|
+
expect(response.data).toStrictEqual(user);
|
|
115
|
+
expect(response.error).toBeNull();
|
|
116
|
+
expect(response.status).toBe(200);
|
|
117
|
+
expect(response.success).toBe(true);
|
|
118
|
+
expect(response.extra?.headers["content-type"]).toContain("application/json");
|
|
119
|
+
});
|
|
120
|
+
|
|
121
|
+
it("should apply the request payload mapper before encoding", async () => {
|
|
122
|
+
const captured = captureRequest("post", "user/byId");
|
|
123
|
+
|
|
124
|
+
await createQuery()
|
|
125
|
+
.setPayload({ id: 1 })
|
|
126
|
+
.setPayloadMapper((payload) => ({ id: (payload?.id ?? 0) + 1 }))
|
|
127
|
+
.send();
|
|
128
|
+
|
|
129
|
+
expect(captured.body).toBe('{"json":{"id":2}}');
|
|
130
|
+
});
|
|
131
|
+
});
|
|
132
|
+
|
|
133
|
+
describe("when sending a query with GET", () => {
|
|
134
|
+
beforeEach(() => {
|
|
135
|
+
client = createClient({ url }).setAdapter(OrpcAdapter({ queryMethod: "GET" }));
|
|
136
|
+
});
|
|
137
|
+
|
|
138
|
+
it("should send the serialized input in the data query param", async () => {
|
|
139
|
+
const captured = captureRequest("get", "user/byId");
|
|
140
|
+
|
|
141
|
+
await createQuery().setPayload({ id: 1 }).send();
|
|
142
|
+
|
|
143
|
+
expect(captured.current?.method).toBe("GET");
|
|
144
|
+
expect(new URL(captured.current?.url as string).searchParams.get("data")).toBe('{"json":{"id":1}}');
|
|
145
|
+
expect(captured.current?.headers.get("content-type")).toBeNull();
|
|
146
|
+
});
|
|
147
|
+
|
|
148
|
+
it("should send the query params next to the input", async () => {
|
|
149
|
+
const captured = captureRequest("get", "user/list");
|
|
150
|
+
|
|
151
|
+
await client
|
|
152
|
+
.createRequest<{ response: User[]; payload: { page: number }; queryParams: { source: string } }>()({
|
|
153
|
+
endpoint: "user/list",
|
|
154
|
+
})
|
|
155
|
+
.setPayload({ page: 2 })
|
|
156
|
+
.setQueryParams({ source: "app" })
|
|
157
|
+
.send();
|
|
158
|
+
|
|
159
|
+
const data = encodeURIComponent('{"json":{"page":2}}');
|
|
160
|
+
expect(captured.current?.url).toBe(`${url}/user/list?source=app&data=${data}`);
|
|
161
|
+
});
|
|
162
|
+
|
|
163
|
+
it("should let a request use POST", async () => {
|
|
164
|
+
const captured = captureRequest("post", "user/byId");
|
|
165
|
+
|
|
166
|
+
await createQuery().setPayload({ id: 1 }).setOptions({ queryMethod: "POST" }).send();
|
|
167
|
+
|
|
168
|
+
expect(captured.current?.method).toBe("POST");
|
|
169
|
+
});
|
|
170
|
+
|
|
171
|
+
it("should send mutations with POST", async () => {
|
|
172
|
+
const captured = captureRequest("post", "user/create");
|
|
173
|
+
|
|
174
|
+
await createMutation().setPayload({ name: "John" }).send();
|
|
175
|
+
|
|
176
|
+
expect(captured.current?.method).toBe("POST");
|
|
177
|
+
expect(captured.body).toBe('{"json":{"name":"John"}}');
|
|
178
|
+
});
|
|
179
|
+
});
|
|
180
|
+
|
|
181
|
+
describe("when a request opts into GET", () => {
|
|
182
|
+
it("should send only that request with GET", async () => {
|
|
183
|
+
const get = captureRequest("get", "user/byId");
|
|
184
|
+
|
|
185
|
+
await createQuery().setPayload({ id: 1 }).setOptions({ queryMethod: "GET" }).send();
|
|
186
|
+
|
|
187
|
+
expect(get.current?.method).toBe("GET");
|
|
188
|
+
});
|
|
189
|
+
});
|
|
190
|
+
|
|
191
|
+
describe("when sending a mutation", () => {
|
|
192
|
+
it("should use the submit dispatcher and not deduplicate by default", () => {
|
|
193
|
+
const request = createMutation();
|
|
194
|
+
|
|
195
|
+
expect(getRequestDispatcher(request)[1]).toBe(false);
|
|
196
|
+
expect(request.deduplicate).toBe(false);
|
|
197
|
+
});
|
|
198
|
+
|
|
199
|
+
it("should send an empty object without an input", async () => {
|
|
200
|
+
const captured = captureRequest("post", "user/reset");
|
|
201
|
+
|
|
202
|
+
await client.createRequest()({ endpoint: "user/reset", method: "MUTATION" }).send();
|
|
203
|
+
|
|
204
|
+
expect(captured.current?.headers.get("content-type")).toBe("application/json");
|
|
205
|
+
expect(captured.body).toBe("{}");
|
|
206
|
+
});
|
|
207
|
+
|
|
208
|
+
it("should report the upload progress with the size of the body", async () => {
|
|
209
|
+
captureRequest("post", "user/create");
|
|
210
|
+
const onUploadProgress = vi.fn();
|
|
211
|
+
|
|
212
|
+
await createMutation().setPayload({ name: "Józef" }).send({ onUploadProgress });
|
|
213
|
+
|
|
214
|
+
const size = new Blob(['{"json":{"name":"Józef"}}']).size;
|
|
215
|
+
expect(onUploadProgress).toHaveBeenCalledWith(expect.objectContaining({ total: size, loaded: size }));
|
|
216
|
+
});
|
|
217
|
+
});
|
|
218
|
+
|
|
219
|
+
describe("when sending files", () => {
|
|
220
|
+
it("should send a multipart body with the files", async () => {
|
|
221
|
+
const captured = captureRequest("post", "files/upload");
|
|
222
|
+
const file = new File(["file content"], "notes.txt", { type: "text/plain" });
|
|
223
|
+
|
|
224
|
+
await client
|
|
225
|
+
.createRequest<{ response: null; payload: { name: string; file: File } }>()({
|
|
226
|
+
endpoint: "files/upload",
|
|
227
|
+
method: "MUTATION",
|
|
228
|
+
})
|
|
229
|
+
.setPayload({ name: "Notes", file })
|
|
230
|
+
.send();
|
|
231
|
+
|
|
232
|
+
expect(captured.current?.headers.get("content-type")).toStartWith("multipart/form-data; boundary=");
|
|
233
|
+
expect(JSON.parse(captured.form?.get("data") as string)).toStrictEqual({
|
|
234
|
+
json: { name: "Notes", file: {} },
|
|
235
|
+
maps: [["file"]],
|
|
236
|
+
});
|
|
237
|
+
const sent = captured.form?.get("0") as File;
|
|
238
|
+
expect(sent.name).toBe("notes.txt");
|
|
239
|
+
expect(await sent.text()).toBe("file content");
|
|
240
|
+
});
|
|
241
|
+
|
|
242
|
+
it("should report the upload progress with the size of the parts", async () => {
|
|
243
|
+
captureRequest("post", "files/upload");
|
|
244
|
+
const onUploadProgress = vi.fn();
|
|
245
|
+
const file = new File(["12345"], "five.txt");
|
|
246
|
+
|
|
247
|
+
await client
|
|
248
|
+
.createRequest<{ response: null; payload: { file: File } }>()({ endpoint: "files/upload", method: "MUTATION" })
|
|
249
|
+
.setPayload({ file })
|
|
250
|
+
.send({ onUploadProgress });
|
|
251
|
+
|
|
252
|
+
const size = new Blob(['{"json":{"file":{}},"maps":[["file"]]}']).size + 5;
|
|
253
|
+
expect(onUploadProgress).toHaveBeenCalledWith(expect.objectContaining({ total: size, loaded: size }));
|
|
254
|
+
});
|
|
255
|
+
|
|
256
|
+
it("should read a multipart response with the files", async () => {
|
|
257
|
+
server.use(
|
|
258
|
+
http.post(`${url}/files/download`, () => {
|
|
259
|
+
const form = new FormData();
|
|
260
|
+
form.set(
|
|
261
|
+
"data",
|
|
262
|
+
JSON.stringify({ json: { file: {}, at: "1970-01-01T00:00:00.000Z" }, meta: [[1, "at"]], maps: [["file"]] }),
|
|
263
|
+
);
|
|
264
|
+
form.set("0", new File(["hello"], "hello.txt", { type: "text/plain" }));
|
|
265
|
+
return new HttpResponse(form);
|
|
266
|
+
}),
|
|
267
|
+
);
|
|
268
|
+
|
|
269
|
+
const response = await client
|
|
270
|
+
.createRequest<{ response: { file: File; at: Date } }>()({ endpoint: "files/download" })
|
|
271
|
+
.send();
|
|
272
|
+
|
|
273
|
+
expect(response.error).toBeNull();
|
|
274
|
+
expect(response.data?.at).toStrictEqual(new Date(0));
|
|
275
|
+
expect(response.data?.file.name).toBe("hello.txt");
|
|
276
|
+
expect(await response.data?.file.text()).toBe("hello");
|
|
277
|
+
});
|
|
278
|
+
});
|
|
279
|
+
|
|
280
|
+
describe("when using the custom serializers", () => {
|
|
281
|
+
beforeEach(() => {
|
|
282
|
+
client = createClient({ url }).setAdapter(OrpcAdapter({ customJsonSerializers: [moneySerializer] }));
|
|
283
|
+
});
|
|
284
|
+
|
|
285
|
+
it("should serialize the input and deserialize the output", async () => {
|
|
286
|
+
const captured = captureRequest("post", "price", { json: { total: ["EUR", 250] }, meta: [[21, "total"]] });
|
|
287
|
+
|
|
288
|
+
const response = await client
|
|
289
|
+
.createRequest<{ response: { total: Money }; payload: { price: Money } }>()({ endpoint: "price" })
|
|
290
|
+
.setPayload({ price: new Money("USD", 100) })
|
|
291
|
+
.send();
|
|
292
|
+
|
|
293
|
+
expect(JSON.parse(captured.body)).toStrictEqual({ json: { price: ["USD", 100] }, meta: [[21, "price"]] });
|
|
294
|
+
expect(response.data?.total).toStrictEqual(new Money("EUR", 250));
|
|
295
|
+
});
|
|
296
|
+
|
|
297
|
+
it("should keep the serializers of different clients apart", async () => {
|
|
298
|
+
const plainClient = createClient({ url }).setAdapter(OrpcAdapter());
|
|
299
|
+
const captured = captureRequest("post", "price");
|
|
300
|
+
|
|
301
|
+
await plainClient
|
|
302
|
+
.createRequest<{ response: null; payload: { price: Money } }>()({ endpoint: "price" })
|
|
303
|
+
.setPayload({ price: new Money("USD", 100) })
|
|
304
|
+
.send();
|
|
305
|
+
|
|
306
|
+
expect(captured.body).toBe('{"json":{"price":{"currency":"USD","cents":100}}}');
|
|
307
|
+
});
|
|
308
|
+
});
|
|
309
|
+
|
|
310
|
+
describe("when the request fails", () => {
|
|
311
|
+
it("should map the error", async () => {
|
|
312
|
+
server.use(http.post(`${url}/user/byId`, () => HttpResponse.json({ json: notFound }, { status: 404 })));
|
|
313
|
+
|
|
314
|
+
const response = await createQuery().setPayload({ id: 1 }).send();
|
|
315
|
+
|
|
316
|
+
expect(response.data).toBeNull();
|
|
317
|
+
expect(response.error).toStrictEqual(notFound);
|
|
318
|
+
expect(response.status).toBe(404);
|
|
319
|
+
expect(response.success).toBe(false);
|
|
320
|
+
expect(response.extra?.headers["content-type"]).toContain("application/json");
|
|
321
|
+
});
|
|
322
|
+
|
|
323
|
+
it("should fail for a response that did not come from a procedure", async () => {
|
|
324
|
+
server.use(
|
|
325
|
+
http.post(`${url}/user/byId`, () => {
|
|
326
|
+
return new HttpResponse("<html>Bad gateway</html>", {
|
|
327
|
+
status: 502,
|
|
328
|
+
headers: { "content-type": "text/html" },
|
|
329
|
+
});
|
|
330
|
+
}),
|
|
331
|
+
);
|
|
332
|
+
|
|
333
|
+
const response = await createQuery().setPayload({ id: 1 }).send();
|
|
334
|
+
|
|
335
|
+
expect(response.data).toBeNull();
|
|
336
|
+
expect(response.error).toStrictEqual(getErrorMessage());
|
|
337
|
+
expect(response.status).toBe(502);
|
|
338
|
+
expect(response.extra?.headers["content-type"]).toBe("text/html");
|
|
339
|
+
});
|
|
340
|
+
|
|
341
|
+
it("should handle a network error", async () => {
|
|
342
|
+
server.use(http.post(`${url}/user/byId`, () => HttpResponse.error()));
|
|
343
|
+
|
|
344
|
+
const response = await createQuery().setPayload({ id: 1 }).send();
|
|
345
|
+
|
|
346
|
+
expect(response.error).toBeInstanceOf(Error);
|
|
347
|
+
expect(response.status).toBe(0);
|
|
348
|
+
expect(response.extra).toStrictEqual({ headers: {} });
|
|
349
|
+
});
|
|
350
|
+
|
|
351
|
+
it("should report an input that can't be serialized", async () => {
|
|
352
|
+
const failure = new Error("Cannot serialize");
|
|
353
|
+
client = createClient({ url }).setAdapter(
|
|
354
|
+
OrpcAdapter({
|
|
355
|
+
customJsonSerializers: [
|
|
356
|
+
{
|
|
357
|
+
...moneySerializer,
|
|
358
|
+
serialize: () => {
|
|
359
|
+
throw failure;
|
|
360
|
+
},
|
|
361
|
+
},
|
|
362
|
+
],
|
|
363
|
+
}),
|
|
364
|
+
);
|
|
365
|
+
const spy = vi.spyOn(globalThis, "fetch");
|
|
366
|
+
|
|
367
|
+
const response = await client
|
|
368
|
+
.createRequest<{ response: null; payload: Money }>()({ endpoint: "price" })
|
|
369
|
+
.setPayload(new Money("USD", 1))
|
|
370
|
+
.send();
|
|
371
|
+
|
|
372
|
+
expect(response.error).toBe(failure);
|
|
373
|
+
expect(response.status).toBe(0);
|
|
374
|
+
expect(spy).not.toHaveBeenCalled();
|
|
375
|
+
spy.mockRestore();
|
|
376
|
+
});
|
|
377
|
+
|
|
378
|
+
it("should report an output that can't be deserialized with the response status", async () => {
|
|
379
|
+
server.use(http.post(`${url}/user/byId`, () => HttpResponse.json({ json: "x", meta: [[0]] })));
|
|
380
|
+
|
|
381
|
+
const response = await createQuery().setPayload({ id: 1 }).send();
|
|
382
|
+
|
|
383
|
+
expect(response.error).toBeInstanceOf(TypeError);
|
|
384
|
+
expect(response.status).toBe(200);
|
|
385
|
+
expect(response.success).toBe(false);
|
|
386
|
+
});
|
|
387
|
+
});
|
|
388
|
+
});
|