@hyper-fetch/core 9.6.1 → 9.7.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/__tests__/features/adapter/adapter.bindings.progress.spec.ts +120 -0
- package/__tests__/features/adapter/adapter.bindings.spec.ts +4 -6
- package/__tests__/features/adapter/adapter.defaults.spec.ts +87 -0
- package/__tests__/features/adapter/adapter.mapping.spec.ts +257 -0
- package/__tests__/features/cache/cache.lazy-storage.clear.spec.ts +145 -0
- package/__tests__/features/cache/cache.lazy-storage.resilience.spec.ts +667 -0
- package/__tests__/features/cache/cache.scoped-events.spec.ts +183 -0
- package/__tests__/features/cache/cache.semantics.spec.ts +785 -0
- package/__tests__/features/cache/cache.structural-sharing.spec.ts +565 -0
- package/__tests__/features/cache/cache.timing.spec.ts +448 -0
- package/__tests__/features/client/client.clear.spec.ts +313 -0
- package/__tests__/features/client/client.configuration.spec.ts +416 -0
- package/__tests__/features/client/client.hydration.round-trip.spec.ts +324 -0
- package/__tests__/features/client/client.interceptor.spec.ts +54 -45
- package/__tests__/features/client/client.interceptors.pipeline.spec.ts +599 -0
- package/__tests__/features/client/client.user-errors.spec.ts +220 -0
- package/__tests__/features/dispatcher/dispatcher.cleanup.spec.ts +534 -0
- package/__tests__/features/dispatcher/dispatcher.control.spec.ts +381 -0
- package/__tests__/features/dispatcher/dispatcher.modes.spec.ts +527 -0
- package/__tests__/features/dispatcher/dispatcher.offline.spec.ts +278 -0
- package/__tests__/features/dispatcher/dispatcher.queue.spec.ts +35 -12
- package/__tests__/features/dispatcher/dispatcher.reentrancy.spec.ts +309 -0
- package/__tests__/features/dispatcher/dispatcher.response-order.spec.ts +241 -0
- package/__tests__/features/dispatcher/dispatcher.retry-flow.spec.ts +554 -0
- package/__tests__/features/dispatcher/dispatcher.retry-removal.spec.ts +196 -0
- package/__tests__/features/dispatcher/dispatcher.retry.spec.ts +4 -3
- package/__tests__/features/http-adapter/http-adapter.e2e.spec.ts +917 -0
- package/__tests__/features/managers/app/app.manager.events.spec.ts +434 -0
- package/__tests__/features/managers/logger/logger.levels.spec.ts +199 -0
- package/__tests__/features/managers/request/request.manager.abort.spec.ts +449 -0
- package/__tests__/features/mocker/mocker.base.spec.ts +22 -3
- package/__tests__/features/mocker/mocker.errors.spec.ts +99 -0
- package/__tests__/features/mocker/mocker.outcomes.spec.ts +308 -0
- package/__tests__/features/optimistic/optimistic.concurrency.spec.ts +278 -0
- package/__tests__/features/optimistic/optimistic.helpers.spec.ts +307 -0
- package/__tests__/features/optimistic/optimistic.matrix.spec.ts +315 -0
- package/__tests__/features/optimistic/optimistic.races.spec.ts +270 -0
- package/__tests__/features/optimistic/optimistic.random.spec.ts +191 -0
- package/__tests__/features/optimistic/optimistic.rollback.spec.ts +1001 -0
- package/__tests__/features/optimistic/optimistic.typescript.spec.ts +196 -0
- package/__tests__/features/plugin/plugin.lifecycle.spec.ts +457 -0
- package/__tests__/features/request/request.async-mapper-removal.spec.ts +138 -0
- package/__tests__/features/request/request.immutability.spec.ts +259 -0
- package/__tests__/features/request/request.inference.spec.ts +269 -0
- package/__tests__/features/request/request.lifecycle.spec.ts +682 -0
- package/__tests__/features/request/request.optimistic-settlement.spec.ts +35 -17
- package/__tests__/features/request/request.optimistic.spec.ts +12 -1
- package/__tests__/features/request/request.values.spec.ts +408 -0
- package/__tests__/features/sdk/sdk.builder.spec.ts +304 -0
- package/__tests__/features/utils/emitter.listeners.spec.ts +202 -0
- package/__tests__/utils/controlled-adapter.utils.ts +119 -0
- package/__tests__/utils/fixtures.utils.ts +193 -0
- package/__tests__/utils/optimistic.utils.ts +124 -0
- package/dist/adapter/adapter.bindings.d.ts.map +1 -1
- package/dist/adapter/adapter.utils.d.ts.map +1 -1
- package/dist/cache/cache.d.ts +12 -1
- package/dist/cache/cache.d.ts.map +1 -1
- package/dist/cache/cache.events.d.ts +20 -6
- package/dist/cache/cache.events.d.ts.map +1 -1
- package/dist/cache/cache.utils.d.ts +1 -0
- package/dist/cache/cache.utils.d.ts.map +1 -1
- package/dist/client/client.d.ts +3 -3
- package/dist/client/client.d.ts.map +1 -1
- package/dist/client/client.utils.d.ts.map +1 -1
- package/dist/dispatcher/dispatcher.d.ts +26 -5
- package/dist/dispatcher/dispatcher.d.ts.map +1 -1
- package/dist/http-adapter/http-adapter.fetch.d.ts.map +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.mjs +2787 -1893
- package/dist/index.mjs.map +1 -1
- package/dist/managers/app/app.manager.constants.d.ts.map +1 -1
- package/dist/managers/app/app.manager.d.ts +9 -0
- package/dist/managers/app/app.manager.d.ts.map +1 -1
- package/dist/managers/app/app.manager.utils.d.ts.map +1 -1
- package/dist/managers/logger/logger.manager.d.ts.map +1 -1
- package/dist/managers/request/request.manager.d.ts.map +1 -1
- package/dist/managers/request/request.manager.types.d.ts +2 -0
- package/dist/managers/request/request.manager.types.d.ts.map +1 -1
- package/dist/mocker/mocker.d.ts +1 -1
- package/dist/mocker/mocker.d.ts.map +1 -1
- package/dist/optimistic/index.d.ts +5 -0
- package/dist/optimistic/index.d.ts.map +1 -0
- package/dist/optimistic/optimistic.d.ts +67 -0
- package/dist/optimistic/optimistic.d.ts.map +1 -0
- package/dist/optimistic/optimistic.settlement.d.ts +60 -0
- package/dist/optimistic/optimistic.settlement.d.ts.map +1 -0
- package/dist/optimistic/optimistic.types.d.ts +109 -0
- package/dist/optimistic/optimistic.types.d.ts.map +1 -0
- package/dist/optimistic/optimistic.utils.d.ts +29 -0
- package/dist/optimistic/optimistic.utils.d.ts.map +1 -0
- package/dist/plugin/plugin.d.ts +2 -0
- package/dist/plugin/plugin.d.ts.map +1 -1
- package/dist/request/request.d.ts +14 -6
- package/dist/request/request.d.ts.map +1 -1
- package/dist/request/request.types.d.ts +40 -1
- package/dist/request/request.types.d.ts.map +1 -1
- package/dist/request/request.utils.d.ts.map +1 -1
- package/dist/utils/emitter.utils.d.ts.map +1 -1
- package/dist/utils/error.utils.d.ts +17 -0
- package/dist/utils/error.utils.d.ts.map +1 -0
- package/dist/utils/index.d.ts +1 -0
- package/dist/utils/index.d.ts.map +1 -1
- package/package.json +1 -1
- package/src/adapter/adapter.bindings.ts +46 -18
- package/src/adapter/adapter.utils.ts +47 -7
- package/src/cache/cache.events.ts +24 -8
- package/src/cache/cache.ts +110 -21
- package/src/cache/cache.utils.ts +33 -10
- package/src/client/client.ts +101 -7
- package/src/client/client.utils.ts +10 -4
- package/src/dispatcher/dispatcher.ts +285 -132
- package/src/http-adapter/http-adapter.fetch.ts +15 -3
- package/src/index.ts +4 -0
- package/src/managers/app/app.manager.constants.ts +12 -1
- package/src/managers/app/app.manager.ts +43 -23
- package/src/managers/app/app.manager.utils.ts +8 -4
- package/src/managers/logger/logger.manager.ts +21 -8
- package/src/managers/request/request.manager.ts +7 -1
- package/src/managers/request/request.manager.types.ts +2 -0
- package/src/mocker/mocker.ts +14 -11
- package/src/optimistic/index.ts +4 -0
- package/src/optimistic/optimistic.settlement.ts +406 -0
- package/src/optimistic/optimistic.ts +162 -0
- package/src/optimistic/optimistic.types.ts +175 -0
- package/src/optimistic/optimistic.utils.ts +112 -0
- package/src/plugin/plugin.ts +6 -0
- package/src/request/request.ts +50 -28
- package/src/request/request.types.ts +41 -1
- package/src/request/request.utils.ts +51 -66
- package/src/utils/emitter.utils.ts +9 -2
- package/src/utils/error.utils.ts +29 -0
- package/src/utils/index.ts +1 -0
- package/tsconfig.json +2 -0
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
import { expectTypeOf } from "vitest";
|
|
2
|
+
|
|
3
|
+
import type { ResponseSuccessType } from "adapter";
|
|
4
|
+
import { Client } from "client";
|
|
5
|
+
import type { HttpAdapterType } from "http-adapter";
|
|
6
|
+
import { optimistic } from "optimistic";
|
|
7
|
+
import type { OptimisticOperation } from "optimistic";
|
|
8
|
+
import type { ParamType, RequestInstance } from "request";
|
|
9
|
+
import type { ExtractMutationContextType } from "types";
|
|
10
|
+
|
|
11
|
+
type Todo = { id: number; title: string; done: boolean; likes: number };
|
|
12
|
+
type Feed = { cursor: string | null; total: number; items: Todo[]; title: string };
|
|
13
|
+
|
|
14
|
+
const client = new Client({ url: "http://localhost:3000" });
|
|
15
|
+
const getTodos = client.createRequest<{ response: Todo[] }>()({ endpoint: "/todos" });
|
|
16
|
+
const getFeed = client.createRequest<{ response: Feed }>()({ endpoint: "/feed" });
|
|
17
|
+
const getTodo = client.createRequest<{ response: Todo }>()({ endpoint: "/todos/:todoId" });
|
|
18
|
+
const toggleTodo = client.createRequest<{ response: Todo; payload: { done: boolean } }>()({
|
|
19
|
+
endpoint: "/todos/:todoId",
|
|
20
|
+
method: "PATCH",
|
|
21
|
+
});
|
|
22
|
+
const createTodo = client.createRequest<{ response: Todo; payload: Omit<Todo, "id"> }>()({
|
|
23
|
+
endpoint: "/todos",
|
|
24
|
+
method: "POST",
|
|
25
|
+
});
|
|
26
|
+
|
|
27
|
+
describe("Optimistic [ TypeScript ]", () => {
|
|
28
|
+
describe("when describing changes", () => {
|
|
29
|
+
it("should type the updater and the helpers with the target's data", () => {
|
|
30
|
+
optimistic(getTodos).set((data) => {
|
|
31
|
+
expectTypeOf(data).toEqualTypeOf<Todo[]>();
|
|
32
|
+
return data;
|
|
33
|
+
});
|
|
34
|
+
optimistic(getFeed).set((data) => {
|
|
35
|
+
expectTypeOf(data).toEqualTypeOf<Feed>();
|
|
36
|
+
return data;
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
expectTypeOf(optimistic(getTodos).patch(1, { done: true })).toEqualTypeOf<
|
|
40
|
+
OptimisticOperation<Todo[], RequestInstance>
|
|
41
|
+
>();
|
|
42
|
+
optimistic(getTodos).patch((todo) => {
|
|
43
|
+
expectTypeOf(todo).toEqualTypeOf<Todo>();
|
|
44
|
+
return todo.done;
|
|
45
|
+
}, {});
|
|
46
|
+
// @ts-expect-error patch takes fields of the item only
|
|
47
|
+
optimistic(getTodos).patch(1, { unknown: true });
|
|
48
|
+
// @ts-expect-error patch takes values of the right type
|
|
49
|
+
optimistic(getTodos).patch(1, { done: "yes" });
|
|
50
|
+
|
|
51
|
+
optimistic(getTodos).insert({ id: 4, title: "new", done: false, likes: 0 });
|
|
52
|
+
// @ts-expect-error insert requires a full item
|
|
53
|
+
optimistic(getTodos).insert({ id: 4 });
|
|
54
|
+
|
|
55
|
+
optimistic(getTodos).remove(1);
|
|
56
|
+
optimistic(getTodos).remove("1");
|
|
57
|
+
// @ts-expect-error an id value has to be a string or number like the id
|
|
58
|
+
optimistic(getTodos).remove(true);
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
it("should match by a custom key", () => {
|
|
62
|
+
optimistic(getTodos).remove("todo-1", { key: "title" });
|
|
63
|
+
optimistic(getTodos).patch("todo-1", { done: true }, { key: "title" });
|
|
64
|
+
// @ts-expect-error the key has to be a field of the item
|
|
65
|
+
optimistic(getTodos).remove("todo-1", { key: "slug" });
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
it("should only offer increment for number fields", () => {
|
|
69
|
+
optimistic(getFeed).increment("total", 1);
|
|
70
|
+
optimistic(getTodos).increment(1, "likes", 1);
|
|
71
|
+
// @ts-expect-error title is not a number
|
|
72
|
+
optimistic(getFeed).increment("title", 1);
|
|
73
|
+
// @ts-expect-error done is not a number
|
|
74
|
+
optimistic(getTodos).increment(1, "done", 1);
|
|
75
|
+
});
|
|
76
|
+
|
|
77
|
+
it("should offer list helpers on arrays and .list() on objects", () => {
|
|
78
|
+
// @ts-expect-error the data is an object - name its list first
|
|
79
|
+
optimistic(getFeed).patch(1, { done: true });
|
|
80
|
+
// @ts-expect-error a list has no fields to name
|
|
81
|
+
optimistic(getTodos).list("items");
|
|
82
|
+
|
|
83
|
+
const operation = optimistic(getFeed).list("items").patch(1, { done: true });
|
|
84
|
+
expectTypeOf(operation).toEqualTypeOf<OptimisticOperation<Feed, RequestInstance>>();
|
|
85
|
+
optimistic(getFeed).list("items").insert({ id: 4, title: "new", done: false, likes: 0 });
|
|
86
|
+
// @ts-expect-error total is not an array
|
|
87
|
+
optimistic(getFeed).list("total");
|
|
88
|
+
});
|
|
89
|
+
|
|
90
|
+
it("should reject a target which still needs params", () => {
|
|
91
|
+
// @ts-expect-error params of the target are not set
|
|
92
|
+
optimistic(getTodo);
|
|
93
|
+
// @ts-expect-error params of the target are not set
|
|
94
|
+
optimistic.all(getTodo);
|
|
95
|
+
|
|
96
|
+
optimistic(getTodo.setParams({ todoId: 1 })).set((todo) => ({ ...todo, done: true }));
|
|
97
|
+
optimistic.all(getTodos).remove(1);
|
|
98
|
+
});
|
|
99
|
+
});
|
|
100
|
+
|
|
101
|
+
describe("when describing the undo and the commit", () => {
|
|
102
|
+
it("should type rollback with the target's data", () => {
|
|
103
|
+
optimistic(getTodos)
|
|
104
|
+
.remove(1)
|
|
105
|
+
.rollback((args) => {
|
|
106
|
+
expectTypeOf(args.data).toEqualTypeOf<Todo[]>();
|
|
107
|
+
expectTypeOf(args.previous).toEqualTypeOf<Todo[]>();
|
|
108
|
+
expectTypeOf(args.reason).toEqualTypeOf<"error" | "abort" | "removed">();
|
|
109
|
+
if (args.reason === "removed") {
|
|
110
|
+
expectTypeOf(args.response).toEqualTypeOf<undefined>();
|
|
111
|
+
}
|
|
112
|
+
return args.data;
|
|
113
|
+
});
|
|
114
|
+
|
|
115
|
+
optimistic(getTodos)
|
|
116
|
+
.remove(1)
|
|
117
|
+
.rollback(() => {});
|
|
118
|
+
// @ts-expect-error rollback returns the target's data
|
|
119
|
+
optimistic(getTodos).remove(1).rollback(() => "wrong");
|
|
120
|
+
});
|
|
121
|
+
|
|
122
|
+
it("should type commit with the mutation's response through the callback's builder", () => {
|
|
123
|
+
createTodo.setOptimistic(({ payload, optimistic: typed }) => {
|
|
124
|
+
expectTypeOf(payload).toEqualTypeOf<Omit<Todo, "id">>();
|
|
125
|
+
return [
|
|
126
|
+
typed(getTodos)
|
|
127
|
+
.insert({ id: -1, ...payload })
|
|
128
|
+
.commit(({ data, response, request }) => {
|
|
129
|
+
expectTypeOf(response).toEqualTypeOf<ResponseSuccessType<Todo, HttpAdapterType>>();
|
|
130
|
+
expectTypeOf(request).toEqualTypeOf<typeof createTodo>();
|
|
131
|
+
return data.map((todo) => (todo.id === -1 ? response.data : todo));
|
|
132
|
+
})
|
|
133
|
+
.rollback(({ data, response }) => {
|
|
134
|
+
if (response) {
|
|
135
|
+
expectTypeOf(response.data).toEqualTypeOf<Todo | null>();
|
|
136
|
+
}
|
|
137
|
+
return data;
|
|
138
|
+
}),
|
|
139
|
+
];
|
|
140
|
+
});
|
|
141
|
+
});
|
|
142
|
+
});
|
|
143
|
+
|
|
144
|
+
describe("when returning from setOptimistic", () => {
|
|
145
|
+
it("should type the callback arguments with the mutation", () => {
|
|
146
|
+
toggleTodo.setOptimistic(({ params, payload, request }) => {
|
|
147
|
+
expectTypeOf(params).toEqualTypeOf<{ todoId: ParamType }>();
|
|
148
|
+
expectTypeOf(payload).toEqualTypeOf<{ done: boolean }>();
|
|
149
|
+
expectTypeOf(request).toEqualTypeOf<typeof toggleTodo>();
|
|
150
|
+
return [optimistic(getTodos).patch(params.todoId, payload)];
|
|
151
|
+
});
|
|
152
|
+
});
|
|
153
|
+
|
|
154
|
+
it("should accept the array, the object and the combined form", () => {
|
|
155
|
+
const withArray = toggleTodo.setOptimistic(() => [optimistic(getTodos).remove(1)]);
|
|
156
|
+
const withObject = toggleTodo.setOptimistic(() => ({ context: { id: 1 }, rollback: () => {} }));
|
|
157
|
+
const combined = toggleTodo.setOptimistic(() => ({
|
|
158
|
+
context: { id: 1 },
|
|
159
|
+
updates: [optimistic(getTodos).remove(1), optimistic(getFeed).increment("total", -1)],
|
|
160
|
+
rollbackOnError: ({ response }) => response.status !== 409,
|
|
161
|
+
revalidate: false,
|
|
162
|
+
}));
|
|
163
|
+
|
|
164
|
+
expectTypeOf<ExtractMutationContextType<typeof withArray>>().toEqualTypeOf<undefined>();
|
|
165
|
+
expectTypeOf<ExtractMutationContextType<typeof withObject>>().toEqualTypeOf<{ id: number }>();
|
|
166
|
+
expectTypeOf<ExtractMutationContextType<typeof combined>>().toEqualTypeOf<{ id: number }>();
|
|
167
|
+
|
|
168
|
+
// @ts-expect-error updates have to be operations
|
|
169
|
+
toggleTodo.setOptimistic(() => ({ updates: [{ id: 1 }] }));
|
|
170
|
+
// @ts-expect-error revalidate is a boolean
|
|
171
|
+
toggleTodo.setOptimistic(() => ({ revalidate: "no" }));
|
|
172
|
+
});
|
|
173
|
+
|
|
174
|
+
it("should accept optimistic per call", () => {
|
|
175
|
+
const sendToggle = () =>
|
|
176
|
+
toggleTodo.send({
|
|
177
|
+
params: { todoId: 1 },
|
|
178
|
+
payload: { done: true },
|
|
179
|
+
optimistic: [optimistic(getTodos).patch(1, { done: true })],
|
|
180
|
+
});
|
|
181
|
+
const sendWithCallback = () =>
|
|
182
|
+
toggleTodo.send({
|
|
183
|
+
params: { todoId: 1 },
|
|
184
|
+
payload: { done: true },
|
|
185
|
+
optimistic: ({ payload }) => [optimistic(getTodos).patch(1, payload)],
|
|
186
|
+
});
|
|
187
|
+
|
|
188
|
+
expectTypeOf(sendToggle).toBeFunction();
|
|
189
|
+
expectTypeOf(sendWithCallback).toBeFunction();
|
|
190
|
+
const sendInvalid = () =>
|
|
191
|
+
// @ts-expect-error per-call optimistic takes operations or a callback
|
|
192
|
+
toggleTodo.send({ params: { todoId: 1 }, payload: { done: true }, optimistic: [1] });
|
|
193
|
+
expectTypeOf(sendInvalid).toBeFunction();
|
|
194
|
+
});
|
|
195
|
+
});
|
|
196
|
+
});
|
|
@@ -0,0 +1,457 @@
|
|
|
1
|
+
import type { Cache } from "cache";
|
|
2
|
+
import { Client } from "client";
|
|
3
|
+
import type { HttpAdapterType } from "http-adapter";
|
|
4
|
+
import { LoggerManager } from "managers";
|
|
5
|
+
import type { PluginMethods } from "plugin";
|
|
6
|
+
import { Plugin } from "plugin";
|
|
7
|
+
|
|
8
|
+
import { createCacheResponse, getThrownErrors, getUnhandledRejections } from "../../utils/fixtures.utils";
|
|
9
|
+
|
|
10
|
+
type Data = { id: number };
|
|
11
|
+
|
|
12
|
+
const requestHooks = [
|
|
13
|
+
"onRequestTrigger",
|
|
14
|
+
"onRequestStart",
|
|
15
|
+
"onRequestSuccess",
|
|
16
|
+
"onRequestError",
|
|
17
|
+
"onRequestFinished",
|
|
18
|
+
"onCacheItemChange",
|
|
19
|
+
] as const;
|
|
20
|
+
|
|
21
|
+
const allHooks = [
|
|
22
|
+
"onMount",
|
|
23
|
+
"onUnmount",
|
|
24
|
+
"onRequestCreate",
|
|
25
|
+
"onRequestTrigger",
|
|
26
|
+
"onRequestStart",
|
|
27
|
+
"onRequestSuccess",
|
|
28
|
+
"onRequestError",
|
|
29
|
+
"onRequestFinished",
|
|
30
|
+
"onDispatcherCleared",
|
|
31
|
+
"onDispatcherQueueDrained",
|
|
32
|
+
"onDispatcherQueueRunning",
|
|
33
|
+
"onDispatcherItemAdded",
|
|
34
|
+
"onDispatcherItemDeleted",
|
|
35
|
+
"onDispatcherQueueCreated",
|
|
36
|
+
"onDispatcherQueueCleared",
|
|
37
|
+
"onCacheItemChange",
|
|
38
|
+
"onCacheItemDelete",
|
|
39
|
+
"onCacheItemInvalidate",
|
|
40
|
+
"onAdapterFetch",
|
|
41
|
+
] as const satisfies readonly (keyof PluginMethods<Client>)[];
|
|
42
|
+
|
|
43
|
+
/** Plugin which records the order of the request lifecycle hooks */
|
|
44
|
+
const createRecorder = (name: string, order: string[]) => {
|
|
45
|
+
const plugin = new Plugin({ name });
|
|
46
|
+
requestHooks.forEach((hook) => {
|
|
47
|
+
plugin[hook](() => {
|
|
48
|
+
order.push(`${name}:${hook}`);
|
|
49
|
+
});
|
|
50
|
+
});
|
|
51
|
+
return plugin;
|
|
52
|
+
};
|
|
53
|
+
|
|
54
|
+
describe("Plugin [ Lifecycle ]", () => {
|
|
55
|
+
let client = new Client({ url: "shared-base-url" });
|
|
56
|
+
let request = client.createRequest<{ response: Data }>()({ endpoint: "/users" });
|
|
57
|
+
|
|
58
|
+
beforeEach(() => {
|
|
59
|
+
client = new Client({ url: "shared-base-url" });
|
|
60
|
+
request = client.createRequest<{ response: Data }>()({ endpoint: "/users" });
|
|
61
|
+
request.setMock(() => ({ data: { id: 1 }, status: 200 }));
|
|
62
|
+
});
|
|
63
|
+
|
|
64
|
+
afterEach(() => {
|
|
65
|
+
client.clear();
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
describe("When the plugin is registered", () => {
|
|
69
|
+
it("should return the plugin from every hook method", () => {
|
|
70
|
+
const plugin = new Plugin({ name: "chain" });
|
|
71
|
+
|
|
72
|
+
allHooks.forEach((hook) => {
|
|
73
|
+
expect(plugin[hook](() => {})).toBe(plugin);
|
|
74
|
+
});
|
|
75
|
+
});
|
|
76
|
+
|
|
77
|
+
it("should trigger the callback registered with every hook method", () => {
|
|
78
|
+
const plugin = new Plugin({ name: "trigger" });
|
|
79
|
+
const spies = allHooks.map((hook) => {
|
|
80
|
+
const spy = vi.fn();
|
|
81
|
+
plugin[hook](spy);
|
|
82
|
+
return spy;
|
|
83
|
+
});
|
|
84
|
+
const data = { client } as never;
|
|
85
|
+
|
|
86
|
+
allHooks.forEach((hook) => plugin.trigger(hook, data));
|
|
87
|
+
|
|
88
|
+
spies.forEach((spy) => {
|
|
89
|
+
expect(spy).toHaveBeenCalledTimes(1);
|
|
90
|
+
expect(spy).toHaveBeenCalledWith(data);
|
|
91
|
+
});
|
|
92
|
+
});
|
|
93
|
+
|
|
94
|
+
it("should use only the latest callback of the hook", () => {
|
|
95
|
+
const first = vi.fn();
|
|
96
|
+
const second = vi.fn();
|
|
97
|
+
const plugin = new Plugin({ name: "replace" }).onRequestCreate(first).onRequestCreate(second);
|
|
98
|
+
client.addPlugin(plugin);
|
|
99
|
+
|
|
100
|
+
client.createRequest()({ endpoint: "/users" });
|
|
101
|
+
|
|
102
|
+
expect(first).not.toHaveBeenCalled();
|
|
103
|
+
expect(second).toHaveBeenCalledTimes(1);
|
|
104
|
+
});
|
|
105
|
+
|
|
106
|
+
it("should keep the name and the data of the plugin", () => {
|
|
107
|
+
const data = { requests: 0 };
|
|
108
|
+
const plugin = new Plugin({ name: "data", data });
|
|
109
|
+
|
|
110
|
+
expect(plugin.name).toBe("data");
|
|
111
|
+
expect(plugin.data).toBe(data);
|
|
112
|
+
expect(plugin.client).toBeUndefined();
|
|
113
|
+
});
|
|
114
|
+
|
|
115
|
+
it("should mount the plugin with the client", () => {
|
|
116
|
+
const onMount = vi.fn();
|
|
117
|
+
const plugin = new Plugin({ name: "mount" }).onMount(onMount);
|
|
118
|
+
|
|
119
|
+
client.addPlugin(plugin);
|
|
120
|
+
|
|
121
|
+
expect(onMount).toHaveBeenCalledTimes(1);
|
|
122
|
+
expect(onMount).toHaveBeenCalledWith({ client });
|
|
123
|
+
expect(plugin.client).toBe(client);
|
|
124
|
+
expect(client.plugins).toStrictEqual([plugin]);
|
|
125
|
+
});
|
|
126
|
+
|
|
127
|
+
it("should unmount the removed plugin", () => {
|
|
128
|
+
const onUnmount = vi.fn();
|
|
129
|
+
const plugin = new Plugin({ name: "unmount" }).onUnmount(onUnmount);
|
|
130
|
+
client.addPlugin(plugin);
|
|
131
|
+
|
|
132
|
+
client.removePlugin(plugin);
|
|
133
|
+
|
|
134
|
+
expect(onUnmount).toHaveBeenCalledTimes(1);
|
|
135
|
+
expect(onUnmount).toHaveBeenCalledWith({ client });
|
|
136
|
+
expect(client.plugins).toHaveLength(0);
|
|
137
|
+
});
|
|
138
|
+
|
|
139
|
+
it("should not unmount the plugin which was never added", () => {
|
|
140
|
+
const onUnmount = vi.fn();
|
|
141
|
+
const added = new Plugin({ name: "added" });
|
|
142
|
+
client.addPlugin(added);
|
|
143
|
+
|
|
144
|
+
client.removePlugin(new Plugin({ name: "unknown" }).onUnmount(onUnmount));
|
|
145
|
+
|
|
146
|
+
expect(onUnmount).not.toHaveBeenCalled();
|
|
147
|
+
expect(client.plugins).toStrictEqual([added]);
|
|
148
|
+
});
|
|
149
|
+
|
|
150
|
+
it("should not unmount the plugin twice", () => {
|
|
151
|
+
const onUnmount = vi.fn();
|
|
152
|
+
const plugin = new Plugin({ name: "unmount" }).onUnmount(onUnmount);
|
|
153
|
+
client.addPlugin(plugin);
|
|
154
|
+
|
|
155
|
+
client.removePlugin(plugin);
|
|
156
|
+
client.removePlugin(plugin);
|
|
157
|
+
|
|
158
|
+
expect(onUnmount).toHaveBeenCalledTimes(1);
|
|
159
|
+
});
|
|
160
|
+
|
|
161
|
+
it("should not notify the removed plugin anymore", async () => {
|
|
162
|
+
const spy = vi.fn();
|
|
163
|
+
const plugin = new Plugin({ name: "removed" }).onRequestCreate(spy).onRequestStart(spy).onCacheItemChange(spy);
|
|
164
|
+
client.addPlugin(plugin);
|
|
165
|
+
client.removePlugin(plugin);
|
|
166
|
+
|
|
167
|
+
client.createRequest()({ endpoint: "/other" });
|
|
168
|
+
await request.send();
|
|
169
|
+
|
|
170
|
+
expect(spy).not.toHaveBeenCalled();
|
|
171
|
+
});
|
|
172
|
+
|
|
173
|
+
it("should notify the plugin about the requests created after it was added", () => {
|
|
174
|
+
const spy = vi.fn();
|
|
175
|
+
client.addPlugin(new Plugin({ name: "create" }).onRequestCreate(spy));
|
|
176
|
+
|
|
177
|
+
const created = client.createRequest()({ endpoint: "/created" });
|
|
178
|
+
|
|
179
|
+
expect(spy).toHaveBeenCalledTimes(1);
|
|
180
|
+
expect(spy).toHaveBeenCalledWith({ request: created });
|
|
181
|
+
});
|
|
182
|
+
});
|
|
183
|
+
|
|
184
|
+
describe("When the request is sent", () => {
|
|
185
|
+
it("should trigger the hooks of the successful request in order", async () => {
|
|
186
|
+
const order: string[] = [];
|
|
187
|
+
client.addPlugin(createRecorder("plugin", order));
|
|
188
|
+
|
|
189
|
+
await request.send();
|
|
190
|
+
|
|
191
|
+
expect(order).toStrictEqual([
|
|
192
|
+
"plugin:onRequestTrigger",
|
|
193
|
+
"plugin:onRequestStart",
|
|
194
|
+
"plugin:onRequestSuccess",
|
|
195
|
+
"plugin:onRequestFinished",
|
|
196
|
+
"plugin:onCacheItemChange",
|
|
197
|
+
]);
|
|
198
|
+
});
|
|
199
|
+
|
|
200
|
+
it("should trigger the hooks of the failed request in order", async () => {
|
|
201
|
+
const order: string[] = [];
|
|
202
|
+
request.setMock(() => ({ error: new Error("Failed"), status: 400 }));
|
|
203
|
+
client.addPlugin(createRecorder("plugin", order));
|
|
204
|
+
|
|
205
|
+
await request.send();
|
|
206
|
+
|
|
207
|
+
expect(order).toStrictEqual([
|
|
208
|
+
"plugin:onRequestTrigger",
|
|
209
|
+
"plugin:onRequestStart",
|
|
210
|
+
"plugin:onRequestError",
|
|
211
|
+
"plugin:onRequestFinished",
|
|
212
|
+
]);
|
|
213
|
+
});
|
|
214
|
+
|
|
215
|
+
it("should trigger every hook for the plugins in the order they were added", async () => {
|
|
216
|
+
const order: string[] = [];
|
|
217
|
+
client.addPlugin(createRecorder("first", order)).addPlugin(createRecorder("second", order));
|
|
218
|
+
|
|
219
|
+
await request.send();
|
|
220
|
+
|
|
221
|
+
expect(order).toStrictEqual(
|
|
222
|
+
["onRequestTrigger", "onRequestStart", "onRequestSuccess", "onRequestFinished", "onCacheItemChange"].flatMap(
|
|
223
|
+
(hook) => [`first:${hook}`, `second:${hook}`],
|
|
224
|
+
),
|
|
225
|
+
);
|
|
226
|
+
});
|
|
227
|
+
|
|
228
|
+
it("should pass the response modified by the interceptors to the plugins", async () => {
|
|
229
|
+
const onRequestSuccess = vi.fn();
|
|
230
|
+
const onRequestFinished = vi.fn();
|
|
231
|
+
client.onResponse((response) => ({ ...response, data: { id: 2 } }));
|
|
232
|
+
client.addPlugin(
|
|
233
|
+
new Plugin({ name: "response" }).onRequestSuccess(onRequestSuccess).onRequestFinished(onRequestFinished),
|
|
234
|
+
);
|
|
235
|
+
|
|
236
|
+
const response = await request.send();
|
|
237
|
+
|
|
238
|
+
expect(onRequestSuccess.mock.calls[0][0].response).toStrictEqual(response);
|
|
239
|
+
expect(onRequestFinished.mock.calls[0][0].response.data).toStrictEqual({ id: 2 });
|
|
240
|
+
});
|
|
241
|
+
|
|
242
|
+
it("should trigger the adapter hook for every sent request", async () => {
|
|
243
|
+
const onAdapterFetch = vi.fn();
|
|
244
|
+
client.addPlugin(new Plugin({ name: "adapter" }).onAdapterFetch(onAdapterFetch));
|
|
245
|
+
|
|
246
|
+
await request.send();
|
|
247
|
+
await request.exec();
|
|
248
|
+
|
|
249
|
+
expect(onAdapterFetch).toHaveBeenCalledTimes(2);
|
|
250
|
+
expect(onAdapterFetch.mock.calls[0][0].adapter).toBe(client.adapter);
|
|
251
|
+
});
|
|
252
|
+
});
|
|
253
|
+
|
|
254
|
+
describe("When the cache changes", () => {
|
|
255
|
+
it("should trigger the delete hook", () => {
|
|
256
|
+
const onCacheItemDelete = vi.fn();
|
|
257
|
+
client.addPlugin(new Plugin({ name: "cache" }).onCacheItemDelete(onCacheItemDelete));
|
|
258
|
+
client.cache.set(request, createCacheResponse({ id: 1 }));
|
|
259
|
+
|
|
260
|
+
client.cache.delete(request.cacheKey);
|
|
261
|
+
|
|
262
|
+
expect(onCacheItemDelete).toHaveBeenCalledTimes(1);
|
|
263
|
+
expect(onCacheItemDelete).toHaveBeenCalledWith({ cache: client.cache, cacheKey: request.cacheKey });
|
|
264
|
+
});
|
|
265
|
+
|
|
266
|
+
it("should trigger the invalidate hook", () => {
|
|
267
|
+
const onCacheItemInvalidate = vi.fn();
|
|
268
|
+
client.addPlugin(new Plugin({ name: "cache" }).onCacheItemInvalidate(onCacheItemInvalidate));
|
|
269
|
+
client.cache.set(request, createCacheResponse({ id: 1 }));
|
|
270
|
+
|
|
271
|
+
client.cache.invalidate(request.cacheKey);
|
|
272
|
+
|
|
273
|
+
expect(onCacheItemInvalidate).toHaveBeenCalledTimes(1);
|
|
274
|
+
expect(onCacheItemInvalidate).toHaveBeenCalledWith({ cache: client.cache, cacheKey: request.cacheKey });
|
|
275
|
+
});
|
|
276
|
+
|
|
277
|
+
it("should trigger the invalidate hook for every invalidated element", () => {
|
|
278
|
+
const onCacheItemInvalidate = vi.fn();
|
|
279
|
+
client.addPlugin(new Plugin({ name: "cache" }).onCacheItemInvalidate(onCacheItemInvalidate));
|
|
280
|
+
client.cache.set(request.setCacheKey("first"), createCacheResponse({ id: 1 }));
|
|
281
|
+
client.cache.set(request.setCacheKey("second"), createCacheResponse({ id: 2 }));
|
|
282
|
+
|
|
283
|
+
client.cache.invalidate();
|
|
284
|
+
|
|
285
|
+
expect(onCacheItemInvalidate.mock.calls.map(([data]) => data.cacheKey)).toStrictEqual(["first", "second"]);
|
|
286
|
+
});
|
|
287
|
+
|
|
288
|
+
it("should trigger the invalidate hook before the listeners", () => {
|
|
289
|
+
const order: string[] = [];
|
|
290
|
+
client.addPlugin(new Plugin({ name: "cache" }).onCacheItemInvalidate(() => order.push("plugin")));
|
|
291
|
+
client.cache.events.onInvalidate(() => order.push("listener"));
|
|
292
|
+
|
|
293
|
+
client.cache.invalidate(request.cacheKey);
|
|
294
|
+
|
|
295
|
+
expect(order).toStrictEqual(["plugin", "listener"]);
|
|
296
|
+
});
|
|
297
|
+
});
|
|
298
|
+
|
|
299
|
+
describe("When the plugin throws", () => {
|
|
300
|
+
const pluginError = new Error("Plugin failed");
|
|
301
|
+
const failingPlugin = (hook: (typeof requestHooks)[number]) =>
|
|
302
|
+
new Plugin({ name: "failing" })[hook](() => {
|
|
303
|
+
throw pluginError;
|
|
304
|
+
});
|
|
305
|
+
|
|
306
|
+
it.each([
|
|
307
|
+
"onRequestTrigger",
|
|
308
|
+
"onRequestStart",
|
|
309
|
+
"onRequestSuccess",
|
|
310
|
+
"onRequestFinished",
|
|
311
|
+
"onCacheItemChange",
|
|
312
|
+
] as const)("should finish the successful request when the %s hook throws", async (hook) => {
|
|
313
|
+
client.addPlugin(failingPlugin(hook));
|
|
314
|
+
|
|
315
|
+
let response: Awaited<ReturnType<typeof request.send>> | undefined;
|
|
316
|
+
let rejections: unknown[] = [];
|
|
317
|
+
const thrown = await getThrownErrors(async () => {
|
|
318
|
+
rejections = await getUnhandledRejections(async () => {
|
|
319
|
+
response = await request.send();
|
|
320
|
+
});
|
|
321
|
+
});
|
|
322
|
+
|
|
323
|
+
expect(rejections).toHaveLength(0);
|
|
324
|
+
// The error is not swallowed - it is thrown outside of the request lifecycle
|
|
325
|
+
expect(thrown).toStrictEqual([pluginError]);
|
|
326
|
+
expect(response?.success).toBeTrue();
|
|
327
|
+
expect(response?.data).toStrictEqual({ id: 1 });
|
|
328
|
+
expect(request.read()?.data).toStrictEqual({ id: 1 });
|
|
329
|
+
});
|
|
330
|
+
|
|
331
|
+
it.each(["onRequestError", "onRequestFinished"] as const)(
|
|
332
|
+
"should finish the failed request when the %s hook throws",
|
|
333
|
+
async (hook) => {
|
|
334
|
+
request.setMock(() => ({ error: new Error("Failed"), status: 400 }));
|
|
335
|
+
client.addPlugin(failingPlugin(hook));
|
|
336
|
+
|
|
337
|
+
let response: Awaited<ReturnType<typeof request.send>> | undefined;
|
|
338
|
+
let rejections: unknown[] = [];
|
|
339
|
+
const thrown = await getThrownErrors(async () => {
|
|
340
|
+
rejections = await getUnhandledRejections(async () => {
|
|
341
|
+
response = await request.send();
|
|
342
|
+
});
|
|
343
|
+
});
|
|
344
|
+
|
|
345
|
+
expect(rejections).toHaveLength(0);
|
|
346
|
+
expect(thrown).toStrictEqual([pluginError]);
|
|
347
|
+
expect(response?.success).toBeFalse();
|
|
348
|
+
expect(response?.error?.message).toBe("Failed");
|
|
349
|
+
},
|
|
350
|
+
);
|
|
351
|
+
|
|
352
|
+
it("should notify the next plugins", async () => {
|
|
353
|
+
const order: string[] = [];
|
|
354
|
+
client.addPlugin(failingPlugin("onRequestSuccess")).addPlugin(createRecorder("next", order));
|
|
355
|
+
|
|
356
|
+
const thrown = await getThrownErrors(() => request.send());
|
|
357
|
+
|
|
358
|
+
expect(thrown).toStrictEqual([pluginError]);
|
|
359
|
+
expect(order).toContain("next:onRequestSuccess");
|
|
360
|
+
expect(order).toContain("next:onCacheItemChange");
|
|
361
|
+
});
|
|
362
|
+
|
|
363
|
+
it("should store and emit the cache data when the cache hook throws", async () => {
|
|
364
|
+
const spy = vi.fn();
|
|
365
|
+
client.addPlugin(failingPlugin("onCacheItemChange"));
|
|
366
|
+
client.cache.events.onDataByKey(request.cacheKey, spy);
|
|
367
|
+
|
|
368
|
+
const thrown = await getThrownErrors(() => {
|
|
369
|
+
expect(() => client.cache.set(request, createCacheResponse({ id: 1 }))).not.toThrow();
|
|
370
|
+
});
|
|
371
|
+
|
|
372
|
+
expect(thrown).toStrictEqual([pluginError]);
|
|
373
|
+
|
|
374
|
+
expect(request.read()?.data).toStrictEqual({ id: 1 });
|
|
375
|
+
expect(spy).toHaveBeenCalledTimes(1);
|
|
376
|
+
expect(client.cache.garbageCollectors.size).toBe(1);
|
|
377
|
+
});
|
|
378
|
+
|
|
379
|
+
it("should delete and invalidate the cache data when the cache hooks throw", async () => {
|
|
380
|
+
const deleteSpy = vi.fn();
|
|
381
|
+
const invalidateSpy = vi.fn();
|
|
382
|
+
client.addPlugin(
|
|
383
|
+
new Plugin({ name: "failing" })
|
|
384
|
+
.onCacheItemDelete(() => {
|
|
385
|
+
throw new Error("Plugin failed");
|
|
386
|
+
})
|
|
387
|
+
.onCacheItemInvalidate(() => {
|
|
388
|
+
throw new Error("Plugin failed");
|
|
389
|
+
}),
|
|
390
|
+
);
|
|
391
|
+
client.cache.set(request, createCacheResponse({ id: 1 }));
|
|
392
|
+
client.cache.events.onDelete(deleteSpy);
|
|
393
|
+
client.cache.events.onInvalidate(invalidateSpy);
|
|
394
|
+
|
|
395
|
+
const thrown = await getThrownErrors(() => {
|
|
396
|
+
client.cache.invalidate(request.cacheKey);
|
|
397
|
+
client.cache.delete(request.cacheKey);
|
|
398
|
+
});
|
|
399
|
+
|
|
400
|
+
expect(thrown).toHaveLength(2);
|
|
401
|
+
expect(invalidateSpy).toHaveBeenCalledTimes(1);
|
|
402
|
+
expect(deleteSpy).toHaveBeenCalledTimes(1);
|
|
403
|
+
expect(request.read()).toBeUndefined();
|
|
404
|
+
});
|
|
405
|
+
|
|
406
|
+
it("should log the failure with the name of the plugin and the hook", async () => {
|
|
407
|
+
const logger = vi.fn();
|
|
408
|
+
client.setDebug(true).setLogger(() => new LoggerManager({ logger }));
|
|
409
|
+
client.addPlugin(failingPlugin("onCacheItemChange"));
|
|
410
|
+
|
|
411
|
+
await getThrownErrors(() => {
|
|
412
|
+
client.cache.set(request, createCacheResponse({ id: 1 }));
|
|
413
|
+
});
|
|
414
|
+
|
|
415
|
+
expect(logger).toHaveBeenCalledTimes(1);
|
|
416
|
+
expect(logger.mock.calls[0][0]).toStrictEqual(
|
|
417
|
+
expect.objectContaining({
|
|
418
|
+
level: "error",
|
|
419
|
+
module: "Client",
|
|
420
|
+
title: 'Plugin "failing" failed',
|
|
421
|
+
extra: { plugin: "failing", method: "onCacheItemChange", error: new Error("Plugin failed") },
|
|
422
|
+
}),
|
|
423
|
+
);
|
|
424
|
+
});
|
|
425
|
+
});
|
|
426
|
+
|
|
427
|
+
describe("When the types are checked", () => {
|
|
428
|
+
it("should type the data passed to the hooks", () => {
|
|
429
|
+
const plugin = new Plugin<Client>({ name: "types" });
|
|
430
|
+
|
|
431
|
+
plugin.onMount((data) => {
|
|
432
|
+
expectTypeOf(data.client).toEqualTypeOf<Client>();
|
|
433
|
+
});
|
|
434
|
+
plugin.onCacheItemDelete((data) => {
|
|
435
|
+
expectTypeOf(data.cacheKey).toBeString();
|
|
436
|
+
expectTypeOf(data.cache).toEqualTypeOf<Cache<HttpAdapterType>>();
|
|
437
|
+
});
|
|
438
|
+
plugin.onCacheItemInvalidate((data) => {
|
|
439
|
+
expectTypeOf(data).toEqualTypeOf<{ cacheKey: string; cache: Cache<HttpAdapterType> }>();
|
|
440
|
+
});
|
|
441
|
+
plugin.onRequestSuccess((data) => {
|
|
442
|
+
expectTypeOf(data.response.success).toEqualTypeOf<true>();
|
|
443
|
+
});
|
|
444
|
+
plugin.onRequestError((data) => {
|
|
445
|
+
expectTypeOf(data.response.success).toEqualTypeOf<false>();
|
|
446
|
+
});
|
|
447
|
+
expectTypeOf(plugin.onRequestStart(() => {})).toEqualTypeOf(plugin);
|
|
448
|
+
});
|
|
449
|
+
|
|
450
|
+
it("should type the data of the plugin", () => {
|
|
451
|
+
const plugin = new Plugin<Client, { requests: number }>({ name: "data", data: { requests: 0 } });
|
|
452
|
+
|
|
453
|
+
expectTypeOf(plugin.data).toEqualTypeOf<{ requests: number }>();
|
|
454
|
+
expectTypeOf(plugin.name).toBeString();
|
|
455
|
+
});
|
|
456
|
+
});
|
|
457
|
+
});
|