@hyper-fetch/core 9.6.2 → 9.8.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.typescript.spec.ts +34 -0
- package/__tests__/features/adapter/adapter.utils.spec.ts +10 -0
- package/__tests__/features/cache/cache.utils.spec.ts +18 -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/request/request.cloning.spec.ts +28 -0
- package/__tests__/features/request/request.optimistic.spec.ts +12 -1
- package/__tests__/features/request/request.sending.spec.ts +13 -10
- package/__tests__/type-stress/custom-adapter/custom-adapter.ts +20 -0
- package/__tests__/type-stress/custom-adapter/tsconfig.json +4 -0
- package/__tests__/utils/optimistic.utils.ts +124 -0
- package/dist/cache/cache.d.ts.map +1 -1
- package/dist/client/client.d.ts.map +1 -1
- package/dist/dispatcher/dispatcher.d.ts.map +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.mjs +578 -70
- package/dist/index.mjs.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/request/request.d.ts +13 -5
- 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/types/adapter.types.d.ts +12 -1
- package/dist/types/adapter.types.d.ts.map +1 -1
- package/package.json +2 -2
- package/src/cache/cache.ts +2 -1
- package/src/client/client.ts +2 -0
- package/src/dispatcher/dispatcher.ts +13 -0
- package/src/index.ts +1 -0
- 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/request/request.ts +19 -6
- package/src/request/request.types.ts +41 -1
- package/src/request/request.utils.ts +30 -54
- package/src/types/adapter.types.ts +42 -25
- package/tsconfig.json +2 -0
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { expectTypeOf } from "vitest";
|
|
2
|
+
|
|
3
|
+
import { Adapter } from "adapter";
|
|
4
|
+
import { createClient } from "client";
|
|
5
|
+
import { HttpMethods } from "constants/http.constants";
|
|
6
|
+
import type { ExtractAdapterType, ExtractUnionAdapter } from "types";
|
|
7
|
+
|
|
8
|
+
const createCustomAdapter = () =>
|
|
9
|
+
new Adapter({
|
|
10
|
+
name: "custom-adapter",
|
|
11
|
+
defaultMethod: HttpMethods.GET,
|
|
12
|
+
defaultExtra: {},
|
|
13
|
+
systemErrorStatus: 0,
|
|
14
|
+
systemErrorExtra: {},
|
|
15
|
+
});
|
|
16
|
+
|
|
17
|
+
type CustomAdapter = ReturnType<typeof createCustomAdapter>;
|
|
18
|
+
|
|
19
|
+
describe("Adapter [ TypeScript ]", () => {
|
|
20
|
+
describe("when selecting the adapter of a request", () => {
|
|
21
|
+
it("should keep a single adapter without comparing it", () => {
|
|
22
|
+
// A single adapter is returned as it is - comparing its whole class is too deep for tsgo
|
|
23
|
+
expectTypeOf<ExtractUnionAdapter<CustomAdapter, { method: "unknown" }>>().toEqualTypeOf<CustomAdapter>();
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
it("should type requests of a client with a custom adapter", () => {
|
|
27
|
+
const adapter = createCustomAdapter();
|
|
28
|
+
const client = createClient({ url: "https://api.test.com" }).setAdapter(adapter);
|
|
29
|
+
const request = client.createRequest<{ response: { id: number } }>()({ endpoint: "/users/:userId" });
|
|
30
|
+
|
|
31
|
+
expectTypeOf<ExtractAdapterType<typeof request>>().toEqualTypeOf<CustomAdapter>();
|
|
32
|
+
});
|
|
33
|
+
});
|
|
34
|
+
});
|
|
@@ -29,6 +29,16 @@ describe("Adapter [ Utils ]", () => {
|
|
|
29
29
|
});
|
|
30
30
|
|
|
31
31
|
describe("When using getAdapterPayload util", () => {
|
|
32
|
+
it("should not create a body without a payload", () => {
|
|
33
|
+
expect(getAdapterPayload(undefined)).toBeUndefined();
|
|
34
|
+
});
|
|
35
|
+
it.each([
|
|
36
|
+
[0, "0"],
|
|
37
|
+
[false, "false"],
|
|
38
|
+
["", '""'],
|
|
39
|
+
])("should create a body for the %j payload", (payload, body) => {
|
|
40
|
+
expect(getAdapterPayload(payload)).toBe(body);
|
|
41
|
+
});
|
|
32
42
|
it("should allow to stringify payload", async () => {
|
|
33
43
|
const data = { data: [] };
|
|
34
44
|
|
|
@@ -6,6 +6,24 @@ import type { ResponseDetailsType } from "managers";
|
|
|
6
6
|
|
|
7
7
|
describe("Cache [ Utils ]", () => {
|
|
8
8
|
describe("when getCacheData function is used", () => {
|
|
9
|
+
it.each([[0], [false], [""]])("should keep the %j response data", (data) => {
|
|
10
|
+
const previousResponse = {
|
|
11
|
+
data: "previous",
|
|
12
|
+
error: null,
|
|
13
|
+
status: 200,
|
|
14
|
+
success: true,
|
|
15
|
+
extra: xhrExtra,
|
|
16
|
+
} as unknown as Parameters<typeof getCacheData>[0];
|
|
17
|
+
const response = {
|
|
18
|
+
data,
|
|
19
|
+
error: null,
|
|
20
|
+
status: 200,
|
|
21
|
+
success: true,
|
|
22
|
+
extra: xhrExtra,
|
|
23
|
+
} as unknown as Parameters<typeof getCacheData>[1];
|
|
24
|
+
|
|
25
|
+
expect(getCacheData(previousResponse, response).data).toBe(data);
|
|
26
|
+
});
|
|
9
27
|
it("should not override cache on retry or refresh error response", async () => {
|
|
10
28
|
const previousResponse = {
|
|
11
29
|
data: {},
|
|
@@ -0,0 +1,278 @@
|
|
|
1
|
+
import { waitFor } from "@testing-library/dom";
|
|
2
|
+
|
|
3
|
+
import type { ClientInstance } from "client";
|
|
4
|
+
import { optimistic } from "optimistic";
|
|
5
|
+
import type { OptimisticOperation } from "optimistic";
|
|
6
|
+
import type { RequestInstance } from "request";
|
|
7
|
+
import type { Stats, Todo } from "../../utils/optimistic.utils";
|
|
8
|
+
import { createControlledClient, createTodo, permutations, readCache, seedCache } from "../../utils/optimistic.utils";
|
|
9
|
+
|
|
10
|
+
type State = "pending" | "success" | "error";
|
|
11
|
+
type Message = { id: number; status: "sending" | "failed" };
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* A documented rollback pattern, applied by mutation `index`. `expected` tells what the target holds for the given
|
|
15
|
+
* state of every mutation - the change stays while pending or after success, and is reverted after an error.
|
|
16
|
+
*/
|
|
17
|
+
type Pattern = {
|
|
18
|
+
name: string;
|
|
19
|
+
seed: (targets: Targets) => void;
|
|
20
|
+
operation: (targets: Targets, index: number) => OptimisticOperation<any, RequestInstance>;
|
|
21
|
+
read: (targets: Targets) => unknown;
|
|
22
|
+
expected: (states: State[]) => unknown;
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
type Targets = {
|
|
26
|
+
client: ClientInstance;
|
|
27
|
+
getTodos: RequestInstance;
|
|
28
|
+
getStats: RequestInstance;
|
|
29
|
+
getMessages: RequestInstance;
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
const ITEMS = [1, 2, 3];
|
|
33
|
+
const sortById = <T extends { id: number }>(list: T[] | undefined) => (list ?? []).toSorted((a, b) => a.id - b.id);
|
|
34
|
+
|
|
35
|
+
const patterns: Pattern[] = [
|
|
36
|
+
{
|
|
37
|
+
name: "re-add from previous",
|
|
38
|
+
seed: ({ client, getTodos }) => seedCache(client, getTodos, ITEMS.map((id) => createTodo(id))),
|
|
39
|
+
operation: ({ getTodos }, index) =>
|
|
40
|
+
optimistic(getTodos as RequestInstance)
|
|
41
|
+
.remove(ITEMS[index])
|
|
42
|
+
.rollback(({ data, previous }: { data: Todo[]; previous: Todo[] }) => {
|
|
43
|
+
const removed = previous.find((todo) => todo.id === ITEMS[index]);
|
|
44
|
+
return removed ? [...data, removed] : data;
|
|
45
|
+
}),
|
|
46
|
+
read: ({ client, getTodos }) => sortById(readCache<Todo[]>(client, getTodos)),
|
|
47
|
+
expected: (states) =>
|
|
48
|
+
ITEMS.filter((_, index) => states[index] === undefined || states[index] === "error").map((id) =>
|
|
49
|
+
createTodo(id),
|
|
50
|
+
),
|
|
51
|
+
},
|
|
52
|
+
{
|
|
53
|
+
name: "restore one item",
|
|
54
|
+
seed: ({ client, getTodos }) => seedCache(client, getTodos, ITEMS.map((id) => createTodo(id))),
|
|
55
|
+
operation: ({ getTodos }, index) =>
|
|
56
|
+
optimistic(getTodos as RequestInstance)
|
|
57
|
+
.patch(ITEMS[index], { done: true })
|
|
58
|
+
.rollback(({ data, previous }: { data: Todo[]; previous: Todo[] }) => {
|
|
59
|
+
const before = previous.find((todo) => todo.id === ITEMS[index]);
|
|
60
|
+
return data.map((todo) => (todo.id === ITEMS[index] && before ? before : todo));
|
|
61
|
+
}),
|
|
62
|
+
read: ({ client, getTodos }) => readCache<Todo[]>(client, getTodos),
|
|
63
|
+
expected: (states) =>
|
|
64
|
+
ITEMS.map((id, index) =>
|
|
65
|
+
createTodo(id, { done: states[index] === "pending" || states[index] === "success" }),
|
|
66
|
+
),
|
|
67
|
+
},
|
|
68
|
+
{
|
|
69
|
+
name: "opposite increment",
|
|
70
|
+
seed: ({ client, getStats }) => seedCache(client, getStats, { total: 10, done: 0 }),
|
|
71
|
+
operation: ({ getStats }, index) =>
|
|
72
|
+
optimistic(getStats as RequestInstance)
|
|
73
|
+
.increment("total", index + 1)
|
|
74
|
+
.rollback(({ data }: { data: Stats }) => ({ ...data, total: data.total - (index + 1) })),
|
|
75
|
+
read: ({ client, getStats }) => readCache<Stats>(client, getStats),
|
|
76
|
+
expected: (states) => ({
|
|
77
|
+
total: states.reduce((sum, state, index) => (state === "error" ? sum : sum + index + 1), 10),
|
|
78
|
+
done: 0,
|
|
79
|
+
}),
|
|
80
|
+
},
|
|
81
|
+
{
|
|
82
|
+
name: "mark as failed",
|
|
83
|
+
seed: ({ client, getMessages }) => seedCache(client, getMessages, []),
|
|
84
|
+
operation: ({ getMessages }, index) =>
|
|
85
|
+
optimistic(getMessages as RequestInstance)
|
|
86
|
+
.insert({ id: ITEMS[index], status: "sending" })
|
|
87
|
+
.rollback(({ data, reason }: { data: Message[]; reason: string }) =>
|
|
88
|
+
reason === "error"
|
|
89
|
+
? data.map((message) => (message.id === ITEMS[index] ? { ...message, status: "failed" } : message))
|
|
90
|
+
: data.filter((message) => message.id !== ITEMS[index]),
|
|
91
|
+
),
|
|
92
|
+
read: ({ client, getMessages }) => sortById(readCache<Message[]>(client, getMessages)),
|
|
93
|
+
expected: (states) =>
|
|
94
|
+
states.flatMap((state, index) =>
|
|
95
|
+
state ? [{ id: ITEMS[index], status: state === "error" ? "failed" : "sending" }] : [],
|
|
96
|
+
),
|
|
97
|
+
},
|
|
98
|
+
];
|
|
99
|
+
|
|
100
|
+
const createSetup = (pattern: Pattern) => {
|
|
101
|
+
const { client, calls } = createControlledClient();
|
|
102
|
+
const targets: Targets = {
|
|
103
|
+
client,
|
|
104
|
+
getTodos: client.createRequest<{ response: Todo[] }>()({ endpoint: "/todos" }),
|
|
105
|
+
getStats: client.createRequest<{ response: Stats }>()({ endpoint: "/stats" }),
|
|
106
|
+
getMessages: client.createRequest<{ response: Message[] }>()({ endpoint: "/messages" }),
|
|
107
|
+
};
|
|
108
|
+
pattern.seed(targets);
|
|
109
|
+
const invalidate = vi.spyOn(client.cache, "invalidate");
|
|
110
|
+
const mutation = client.createRequest<{ response: null }>()({ endpoint: "/mutations/:index", method: "POST" });
|
|
111
|
+
|
|
112
|
+
/** Sends mutation `index` and waits until it reaches the network */
|
|
113
|
+
const send = async (index: number) => {
|
|
114
|
+
let requestId = "";
|
|
115
|
+
const promise = mutation.send({
|
|
116
|
+
params: { index },
|
|
117
|
+
optimistic: [pattern.operation(targets, index)],
|
|
118
|
+
onBeforeSent: (data) => {
|
|
119
|
+
requestId = data.requestId;
|
|
120
|
+
},
|
|
121
|
+
});
|
|
122
|
+
await waitFor(
|
|
123
|
+
() => {
|
|
124
|
+
expect(calls.some((call) => call.requestId === requestId)).toBeTrue();
|
|
125
|
+
},
|
|
126
|
+
{ interval: 1 },
|
|
127
|
+
);
|
|
128
|
+
const call = calls.find((item) => item.requestId === requestId)!;
|
|
129
|
+
return { promise, call };
|
|
130
|
+
};
|
|
131
|
+
|
|
132
|
+
return { targets, invalidate, send };
|
|
133
|
+
};
|
|
134
|
+
|
|
135
|
+
const outcomeCombinations = (count: number): ("success" | "error")[][] => {
|
|
136
|
+
if (count === 0) {
|
|
137
|
+
return [[]];
|
|
138
|
+
}
|
|
139
|
+
return outcomeCombinations(count - 1).flatMap((rest) => [
|
|
140
|
+
["success" as const, ...rest],
|
|
141
|
+
["error" as const, ...rest],
|
|
142
|
+
]);
|
|
143
|
+
};
|
|
144
|
+
|
|
145
|
+
const scenarios = [2, 3].flatMap((count) => {
|
|
146
|
+
const indexes = Array.from({ length: count }, (_, index) => index);
|
|
147
|
+
return permutations(indexes).flatMap((order) =>
|
|
148
|
+
outcomeCombinations(count).map((outcomes) => ({ count, order, outcomes })),
|
|
149
|
+
);
|
|
150
|
+
});
|
|
151
|
+
|
|
152
|
+
describe("Optimistic [ Concurrency ]", () => {
|
|
153
|
+
describe.each(patterns)("when using the $name pattern", (pattern) => {
|
|
154
|
+
it.each(scenarios)(
|
|
155
|
+
"should hold the right value after each settle ($count mutations, order $order, outcomes $outcomes)",
|
|
156
|
+
async ({ count, order, outcomes }) => {
|
|
157
|
+
const { targets, invalidate, send } = createSetup(pattern);
|
|
158
|
+
const states: State[] = [];
|
|
159
|
+
const sent = [];
|
|
160
|
+
|
|
161
|
+
for (let index = 0; index < count; index += 1) {
|
|
162
|
+
// eslint-disable-next-line no-await-in-loop
|
|
163
|
+
sent.push(await send(index));
|
|
164
|
+
states[index] = "pending";
|
|
165
|
+
expect(pattern.read(targets)).toStrictEqual(pattern.expected(states));
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
for (const [step, index] of order.entries()) {
|
|
169
|
+
const outcome = outcomes[index];
|
|
170
|
+
sent[index].call.respond(outcome === "success" ? { data: null } : { error: new Error("Failed") });
|
|
171
|
+
// eslint-disable-next-line no-await-in-loop
|
|
172
|
+
await sent[index].promise;
|
|
173
|
+
states[index] = outcome;
|
|
174
|
+
|
|
175
|
+
expect(pattern.read(targets)).toStrictEqual(pattern.expected(states));
|
|
176
|
+
// The refresh waits for the last pending mutation on the key
|
|
177
|
+
expect(invalidate).toHaveBeenCalledTimes(step === count - 1 ? 1 : 0);
|
|
178
|
+
}
|
|
179
|
+
},
|
|
180
|
+
);
|
|
181
|
+
});
|
|
182
|
+
|
|
183
|
+
describe("when two mutations change the same field", () => {
|
|
184
|
+
const createToggles = () => {
|
|
185
|
+
const { client, calls } = createControlledClient();
|
|
186
|
+
const getTodos = client.createRequest<{ response: Todo[] }>()({ endpoint: "/todos" });
|
|
187
|
+
seedCache(client, getTodos, [createTodo(1)]);
|
|
188
|
+
const toggle = client
|
|
189
|
+
.createRequest<{ response: Todo; payload: { done: boolean } }>()({ endpoint: "/todos/:id", method: "PATCH" })
|
|
190
|
+
.setParams({ id: 1 })
|
|
191
|
+
.setOptimistic(({ payload }) => [
|
|
192
|
+
optimistic(getTodos)
|
|
193
|
+
.patch(1, payload)
|
|
194
|
+
.rollback(({ data, previous }) => {
|
|
195
|
+
const before = previous.find((todo) => todo.id === 1);
|
|
196
|
+
return data.map((todo) => (todo.id === 1 && before ? before : todo));
|
|
197
|
+
}),
|
|
198
|
+
]);
|
|
199
|
+
const done = () => readCache<Todo[]>(client, getTodos)?.[0].done;
|
|
200
|
+
return { client, calls, getTodos, toggle, done };
|
|
201
|
+
};
|
|
202
|
+
|
|
203
|
+
it("should restore the value from before the failed toggle, then refresh to the server value", async () => {
|
|
204
|
+
const { client, calls, getTodos, toggle, done } = createToggles();
|
|
205
|
+
const invalidate = vi.spyOn(client.cache, "invalidate");
|
|
206
|
+
|
|
207
|
+
const first = toggle.send({ payload: { done: true } });
|
|
208
|
+
const second = toggle.send({ payload: { done: false } });
|
|
209
|
+
await waitFor(() => expect(calls).toHaveLength(2), { interval: 1 });
|
|
210
|
+
expect(done()).toBeFalse();
|
|
211
|
+
|
|
212
|
+
// The later toggle succeeded, the earlier one fails and restores what it saw: `false`
|
|
213
|
+
calls[1].respond({ data: createTodo(1) });
|
|
214
|
+
await second;
|
|
215
|
+
expect(done()).toBeFalse();
|
|
216
|
+
calls[0].respond({ error: new Error("Failed") });
|
|
217
|
+
await first;
|
|
218
|
+
expect(done()).toBeFalse();
|
|
219
|
+
expect(invalidate).toHaveBeenCalledTimes(1);
|
|
220
|
+
|
|
221
|
+
const refresh = getTodos.send();
|
|
222
|
+
await waitFor(() => expect(calls).toHaveLength(3), { interval: 1 });
|
|
223
|
+
calls[2].respond({ data: [createTodo(1, { done: false })] });
|
|
224
|
+
await refresh;
|
|
225
|
+
expect(done()).toBeFalse();
|
|
226
|
+
});
|
|
227
|
+
|
|
228
|
+
it("should document the rollback of the later toggle overwriting the earlier success", async () => {
|
|
229
|
+
const { calls, getTodos, toggle, done } = createToggles();
|
|
230
|
+
|
|
231
|
+
const first = toggle.send({ payload: { done: true } });
|
|
232
|
+
const second = toggle.send({ payload: { done: false } });
|
|
233
|
+
await waitFor(() => expect(calls).toHaveLength(2), { interval: 1 });
|
|
234
|
+
|
|
235
|
+
calls[0].respond({ data: createTodo(1, { done: true }) });
|
|
236
|
+
await first;
|
|
237
|
+
// The later toggle fails and restores its own previous value - the earlier, successful `true`
|
|
238
|
+
calls[1].respond({ error: new Error("Failed") });
|
|
239
|
+
await second;
|
|
240
|
+
expect(done()).toBeTrue();
|
|
241
|
+
|
|
242
|
+
// The server holds `true` too, so the refresh confirms it
|
|
243
|
+
const refresh = getTodos.send();
|
|
244
|
+
await waitFor(() => expect(calls).toHaveLength(3), { interval: 1 });
|
|
245
|
+
calls[2].respond({ data: [createTodo(1, { done: true })] });
|
|
246
|
+
await refresh;
|
|
247
|
+
expect(done()).toBeTrue();
|
|
248
|
+
});
|
|
249
|
+
});
|
|
250
|
+
|
|
251
|
+
describe("when mutations target different keys", () => {
|
|
252
|
+
it("should refresh each key once its own last mutation settled", async () => {
|
|
253
|
+
const { client, calls } = createControlledClient();
|
|
254
|
+
const getTodos = client.createRequest<{ response: Todo[] }>()({ endpoint: "/todos" });
|
|
255
|
+
const getStats = client.createRequest<{ response: Stats }>()({ endpoint: "/stats" });
|
|
256
|
+
seedCache(client, getTodos, [createTodo(1)]);
|
|
257
|
+
seedCache(client, getStats, { total: 1, done: 0 });
|
|
258
|
+
const invalidate = vi.spyOn(client.cache, "invalidate");
|
|
259
|
+
const mutation = client.createRequest<{ response: null }>()({ endpoint: "/mutation", method: "POST" });
|
|
260
|
+
|
|
261
|
+
const both = mutation.send({
|
|
262
|
+
optimistic: [optimistic(getTodos).patch(1, { done: true }), optimistic(getStats).increment("done", 1)],
|
|
263
|
+
});
|
|
264
|
+
const statsOnly = mutation.send({ optimistic: [optimistic(getStats).increment("total", 1)] });
|
|
265
|
+
await waitFor(() => expect(calls).toHaveLength(2), { interval: 1 });
|
|
266
|
+
|
|
267
|
+
calls[0].respond({ data: null });
|
|
268
|
+
await both;
|
|
269
|
+
expect(invalidate).toHaveBeenCalledTimes(1);
|
|
270
|
+
expect(invalidate).toHaveBeenCalledWith(getTodos);
|
|
271
|
+
|
|
272
|
+
calls[1].respond({ data: null });
|
|
273
|
+
await statsOnly;
|
|
274
|
+
expect(invalidate).toHaveBeenCalledTimes(2);
|
|
275
|
+
expect(invalidate).toHaveBeenLastCalledWith(getStats);
|
|
276
|
+
});
|
|
277
|
+
});
|
|
278
|
+
});
|
|
@@ -0,0 +1,307 @@
|
|
|
1
|
+
import { Client } from "client";
|
|
2
|
+
import { optimistic } from "optimistic";
|
|
3
|
+
import type { OptimisticOperation } from "optimistic";
|
|
4
|
+
|
|
5
|
+
type Todo = { id: number; title: string; done: boolean; likes: number; tags?: string[] };
|
|
6
|
+
type Feed = { cursor: string | null; total: number; items: Todo[]; meta: { pages: number } };
|
|
7
|
+
|
|
8
|
+
const createTodo = (id: number, extra: Partial<Todo> = {}): Todo => ({
|
|
9
|
+
id,
|
|
10
|
+
title: `todo-${id}`,
|
|
11
|
+
done: false,
|
|
12
|
+
likes: 0,
|
|
13
|
+
...extra,
|
|
14
|
+
});
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Operations are pure descriptions - `update` is the transformation core applies to the cached data
|
|
18
|
+
*/
|
|
19
|
+
const apply = <Data>(operation: OptimisticOperation<Data, any>, data: Data): Data => operation.update(data);
|
|
20
|
+
|
|
21
|
+
describe("Optimistic [ Helpers ]", () => {
|
|
22
|
+
const client = new Client({ url: "shared-base-url" });
|
|
23
|
+
const getTodos = client.createRequest<{ response: Todo[] }>()({ endpoint: "/todos" });
|
|
24
|
+
const getFeed = client.createRequest<{ response: Feed }>()({ endpoint: "/feed" });
|
|
25
|
+
const getTodo = client.createRequest<{ response: Todo }>()({ endpoint: "/todos/:todoId" });
|
|
26
|
+
|
|
27
|
+
let list: Todo[];
|
|
28
|
+
let feed: Feed;
|
|
29
|
+
|
|
30
|
+
beforeEach(() => {
|
|
31
|
+
list = [createTodo(1), createTodo(2), createTodo(3)];
|
|
32
|
+
feed = { cursor: "c1", total: 3, items: list, meta: { pages: 1 } };
|
|
33
|
+
});
|
|
34
|
+
|
|
35
|
+
describe("when using set", () => {
|
|
36
|
+
it("should replace the data with the updater result", () => {
|
|
37
|
+
const result = apply(
|
|
38
|
+
optimistic(getTodo.setParams({ todoId: 1 })).set((todo) => ({ ...todo, title: "changed" })),
|
|
39
|
+
list[0],
|
|
40
|
+
);
|
|
41
|
+
|
|
42
|
+
expect(result).toStrictEqual({ ...list[0], title: "changed" });
|
|
43
|
+
expect(list[0].title).toBe("todo-1");
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
it("should pass the data of a list target", () => {
|
|
47
|
+
const updater = vi.fn((todos: Todo[]) => todos.slice(1));
|
|
48
|
+
const result = apply(optimistic(getTodos).set(updater), list);
|
|
49
|
+
|
|
50
|
+
expect(updater).toHaveBeenCalledWith(list);
|
|
51
|
+
expect(result).toStrictEqual([list[1], list[2]]);
|
|
52
|
+
});
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
describe("when using patch", () => {
|
|
56
|
+
it("should patch the item matched by id value", () => {
|
|
57
|
+
const result = apply(optimistic(getTodos).patch(2, { done: true }), list);
|
|
58
|
+
|
|
59
|
+
expect(result).toStrictEqual([list[0], { ...list[1], done: true }, list[2]]);
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
it("should match a string id with a number id like route params do", () => {
|
|
63
|
+
const result = apply(optimistic(getTodos).patch("2", { done: true }), list);
|
|
64
|
+
|
|
65
|
+
expect(result[1].done).toBeTrue();
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
it("should patch the items matched by predicate", () => {
|
|
69
|
+
const result = apply(
|
|
70
|
+
optimistic(getTodos).patch((todo) => todo.id !== 2, { done: true }),
|
|
71
|
+
list,
|
|
72
|
+
);
|
|
73
|
+
|
|
74
|
+
expect(result.map((todo) => todo.done)).toStrictEqual([true, false, true]);
|
|
75
|
+
});
|
|
76
|
+
|
|
77
|
+
it("should match by custom key", () => {
|
|
78
|
+
const result = apply(optimistic(getTodos).patch("todo-3", { done: true }, { key: "title" }), list);
|
|
79
|
+
|
|
80
|
+
expect(result.map((todo) => todo.done)).toStrictEqual([false, false, true]);
|
|
81
|
+
});
|
|
82
|
+
|
|
83
|
+
it("should keep unchanged items referentially equal", () => {
|
|
84
|
+
const result = apply(optimistic(getTodos).patch(2, { done: true }), list);
|
|
85
|
+
|
|
86
|
+
expect(result[0]).toBe(list[0]);
|
|
87
|
+
expect(result[2]).toBe(list[2]);
|
|
88
|
+
expect(result[1]).not.toBe(list[1]);
|
|
89
|
+
});
|
|
90
|
+
|
|
91
|
+
it("should return the same list when nothing matched", () => {
|
|
92
|
+
expect(apply(optimistic(getTodos).patch(99, { done: true }), list)).toBe(list);
|
|
93
|
+
});
|
|
94
|
+
|
|
95
|
+
it("should return the same empty list", () => {
|
|
96
|
+
const empty: Todo[] = [];
|
|
97
|
+
expect(apply(optimistic(getTodos).patch(1, { done: true }), empty)).toBe(empty);
|
|
98
|
+
});
|
|
99
|
+
|
|
100
|
+
it("should patch several matches", () => {
|
|
101
|
+
const duplicated = [createTodo(1), createTodo(1, { title: "twin" }), createTodo(2)];
|
|
102
|
+
const result = apply(optimistic(getTodos).patch(1, { likes: 5 }), duplicated);
|
|
103
|
+
|
|
104
|
+
expect(result.map((todo) => todo.likes)).toStrictEqual([5, 5, 0]);
|
|
105
|
+
});
|
|
106
|
+
|
|
107
|
+
it("should replace nested values instead of merging them deeply", () => {
|
|
108
|
+
const tagged = [createTodo(1, { tags: ["a", "b"] })];
|
|
109
|
+
const result = apply(optimistic(getTodos).patch(1, { tags: ["c"] }), tagged);
|
|
110
|
+
|
|
111
|
+
expect(result[0].tags).toStrictEqual(["c"]);
|
|
112
|
+
});
|
|
113
|
+
|
|
114
|
+
it("should patch the items of a list field", () => {
|
|
115
|
+
const result = apply(optimistic(getFeed).list("items").patch(1, { done: true }), feed);
|
|
116
|
+
|
|
117
|
+
expect(result.items[0].done).toBeTrue();
|
|
118
|
+
expect(result.meta).toBe(feed.meta);
|
|
119
|
+
expect(result.cursor).toBe("c1");
|
|
120
|
+
});
|
|
121
|
+
|
|
122
|
+
it("should return the same object when nothing in a list field matched", () => {
|
|
123
|
+
expect(apply(optimistic(getFeed).list("items").patch(99, { done: true }), feed)).toBe(feed);
|
|
124
|
+
});
|
|
125
|
+
|
|
126
|
+
it("should skip primitives and nulls when matching by value", () => {
|
|
127
|
+
const mixed = [null, 1, createTodo(1)] as unknown as Todo[];
|
|
128
|
+
const result = apply(optimistic(getTodos).patch(1, { done: true }), mixed);
|
|
129
|
+
|
|
130
|
+
expect(result[0]).toBeNull();
|
|
131
|
+
expect(result[1]).toBe(1);
|
|
132
|
+
expect(result[2].done).toBeTrue();
|
|
133
|
+
});
|
|
134
|
+
});
|
|
135
|
+
|
|
136
|
+
describe("when using insert", () => {
|
|
137
|
+
it("should add the item at the end by default", () => {
|
|
138
|
+
const result = apply(optimistic(getTodos).insert(createTodo(4)), list);
|
|
139
|
+
|
|
140
|
+
expect(result.map((todo) => todo.id)).toStrictEqual([1, 2, 3, 4]);
|
|
141
|
+
expect(list).toHaveLength(3);
|
|
142
|
+
});
|
|
143
|
+
|
|
144
|
+
it("should add the item at the start", () => {
|
|
145
|
+
const result = apply(optimistic(getTodos).insert(createTodo(4), { at: "start" }), list);
|
|
146
|
+
|
|
147
|
+
expect(result.map((todo) => todo.id)).toStrictEqual([4, 1, 2, 3]);
|
|
148
|
+
});
|
|
149
|
+
|
|
150
|
+
it("should add the item at the end explicitly", () => {
|
|
151
|
+
const result = apply(optimistic(getTodos).insert(createTodo(4), { at: "end" }), list);
|
|
152
|
+
|
|
153
|
+
expect(result.map((todo) => todo.id)).toStrictEqual([1, 2, 3, 4]);
|
|
154
|
+
});
|
|
155
|
+
|
|
156
|
+
it("should add the item at the index", () => {
|
|
157
|
+
const result = apply(optimistic(getTodos).insert(createTodo(4), { at: 1 }), list);
|
|
158
|
+
|
|
159
|
+
expect(result.map((todo) => todo.id)).toStrictEqual([1, 4, 2, 3]);
|
|
160
|
+
});
|
|
161
|
+
|
|
162
|
+
it("should add the item to an empty list", () => {
|
|
163
|
+
expect(apply(optimistic(getTodos).insert(createTodo(4)), [])).toStrictEqual([createTodo(4)]);
|
|
164
|
+
});
|
|
165
|
+
|
|
166
|
+
it("should add the item to a list field", () => {
|
|
167
|
+
const result = apply(optimistic(getFeed).list("items").insert(createTodo(4), { at: "start" }), feed);
|
|
168
|
+
|
|
169
|
+
expect(result.items.map((todo) => todo.id)).toStrictEqual([4, 1, 2, 3]);
|
|
170
|
+
expect(result.total).toBe(3);
|
|
171
|
+
});
|
|
172
|
+
|
|
173
|
+
it("should create a missing list field", () => {
|
|
174
|
+
const noItems = { ...feed, items: undefined } as unknown as Feed;
|
|
175
|
+
const result = apply(optimistic(getFeed).list("items").insert(createTodo(4)), noItems);
|
|
176
|
+
|
|
177
|
+
expect(result.items).toStrictEqual([createTodo(4)]);
|
|
178
|
+
});
|
|
179
|
+
});
|
|
180
|
+
|
|
181
|
+
describe("when using remove", () => {
|
|
182
|
+
it("should remove the item matched by id value", () => {
|
|
183
|
+
const result = apply(optimistic(getTodos).remove(2), list);
|
|
184
|
+
|
|
185
|
+
expect(result).toStrictEqual([list[0], list[2]]);
|
|
186
|
+
});
|
|
187
|
+
|
|
188
|
+
it("should remove the items matched by predicate", () => {
|
|
189
|
+
const result = apply(
|
|
190
|
+
optimistic(getTodos).remove((todo) => todo.id > 1),
|
|
191
|
+
list,
|
|
192
|
+
);
|
|
193
|
+
|
|
194
|
+
expect(result).toStrictEqual([list[0]]);
|
|
195
|
+
});
|
|
196
|
+
|
|
197
|
+
it("should remove by custom key", () => {
|
|
198
|
+
expect(apply(optimistic(getTodos).remove("todo-1", { key: "title" }), list)).toStrictEqual([list[1], list[2]]);
|
|
199
|
+
});
|
|
200
|
+
|
|
201
|
+
it("should return the same list when nothing matched", () => {
|
|
202
|
+
expect(apply(optimistic(getTodos).remove(99), list)).toBe(list);
|
|
203
|
+
});
|
|
204
|
+
|
|
205
|
+
it("should remove from a list field", () => {
|
|
206
|
+
const result = apply(optimistic(getFeed).list("items").remove(1), feed);
|
|
207
|
+
|
|
208
|
+
expect(result.items.map((todo) => todo.id)).toStrictEqual([2, 3]);
|
|
209
|
+
});
|
|
210
|
+
|
|
211
|
+
it("should keep the object of a missing list field", () => {
|
|
212
|
+
const noItems = { ...feed, items: undefined } as unknown as Feed;
|
|
213
|
+
expect(apply(optimistic(getFeed).list("items").remove(1), noItems)).toBe(noItems);
|
|
214
|
+
});
|
|
215
|
+
});
|
|
216
|
+
|
|
217
|
+
describe("when using increment", () => {
|
|
218
|
+
it("should increment a field of the data", () => {
|
|
219
|
+
const result = apply(optimistic(getFeed).increment("total", -1), feed);
|
|
220
|
+
|
|
221
|
+
expect(result.total).toBe(2);
|
|
222
|
+
expect(result.items).toBe(feed.items);
|
|
223
|
+
});
|
|
224
|
+
|
|
225
|
+
it("should start from zero when the field is missing", () => {
|
|
226
|
+
const noTotal = { ...feed, total: undefined } as unknown as Feed;
|
|
227
|
+
expect(apply(optimistic(getFeed).increment("total", 2), noTotal).total).toBe(2);
|
|
228
|
+
});
|
|
229
|
+
|
|
230
|
+
it("should increment a field of the matched items", () => {
|
|
231
|
+
const result = apply(optimistic(getTodos).increment(2, "likes", 3), list);
|
|
232
|
+
|
|
233
|
+
expect(result.map((todo) => todo.likes)).toStrictEqual([0, 3, 0]);
|
|
234
|
+
expect(result[0]).toBe(list[0]);
|
|
235
|
+
});
|
|
236
|
+
|
|
237
|
+
it("should increment by predicate and custom key", () => {
|
|
238
|
+
const byPredicate = apply(
|
|
239
|
+
optimistic(getTodos).increment((todo) => todo.id < 3, "likes", 1),
|
|
240
|
+
list,
|
|
241
|
+
);
|
|
242
|
+
const byKey = apply(optimistic(getTodos).increment("todo-3", "likes", 1, { key: "title" }), list);
|
|
243
|
+
|
|
244
|
+
expect(byPredicate.map((todo) => todo.likes)).toStrictEqual([1, 1, 0]);
|
|
245
|
+
expect(byKey.map((todo) => todo.likes)).toStrictEqual([0, 0, 1]);
|
|
246
|
+
});
|
|
247
|
+
|
|
248
|
+
it("should return the same list when nothing matched", () => {
|
|
249
|
+
expect(apply(optimistic(getTodos).increment(99, "likes", 1), list)).toBe(list);
|
|
250
|
+
});
|
|
251
|
+
|
|
252
|
+
it("should increment items of a list field", () => {
|
|
253
|
+
const result = apply(optimistic(getFeed).list("items").increment(1, "likes", 2), feed);
|
|
254
|
+
|
|
255
|
+
expect(result.items[0].likes).toBe(2);
|
|
256
|
+
});
|
|
257
|
+
});
|
|
258
|
+
|
|
259
|
+
describe("when the data has the wrong shape", () => {
|
|
260
|
+
it("should throw from list helpers on an object", () => {
|
|
261
|
+
const operation = optimistic(getTodos).patch(1, { done: true });
|
|
262
|
+
|
|
263
|
+
expect(() => apply(operation, feed as unknown as Todo[])).toThrow(TypeError);
|
|
264
|
+
});
|
|
265
|
+
|
|
266
|
+
it("should throw from increment(field, by) on a list", () => {
|
|
267
|
+
const operation = optimistic(getFeed).increment("total", 1);
|
|
268
|
+
|
|
269
|
+
expect(() => apply(operation, list as unknown as Feed)).toThrow(TypeError);
|
|
270
|
+
});
|
|
271
|
+
|
|
272
|
+
it("should throw from a list field that is not an array", () => {
|
|
273
|
+
const broken = { ...feed, items: "nope" } as unknown as Feed;
|
|
274
|
+
|
|
275
|
+
expect(() => apply(optimistic(getFeed).list("items").insert(createTodo(4)), broken)).toThrow(TypeError);
|
|
276
|
+
});
|
|
277
|
+
|
|
278
|
+
it("should throw from a list field of null data", () => {
|
|
279
|
+
expect(() => apply(optimistic(getFeed).list("items").insert(createTodo(4)), null as unknown as Feed)).toThrow(
|
|
280
|
+
TypeError,
|
|
281
|
+
);
|
|
282
|
+
});
|
|
283
|
+
});
|
|
284
|
+
|
|
285
|
+
describe("when chaining", () => {
|
|
286
|
+
it("should return new operations from rollback and commit", () => {
|
|
287
|
+
const base = optimistic(getTodos).remove(1);
|
|
288
|
+
const rollback = () => {};
|
|
289
|
+
const commit = () => {};
|
|
290
|
+
const withRollback = base.rollback(rollback);
|
|
291
|
+
const withBoth = withRollback.commit(commit);
|
|
292
|
+
|
|
293
|
+
expect(base.onRollback).toBeUndefined();
|
|
294
|
+
expect(withRollback.onRollback).toBe(rollback);
|
|
295
|
+
expect(withRollback.onCommit).toBeUndefined();
|
|
296
|
+
expect(withBoth.onRollback).toBe(rollback);
|
|
297
|
+
expect(withBoth.onCommit).toBe(commit);
|
|
298
|
+
expect(withBoth.commit(commit).rollback(rollback).update).toBe(base.update);
|
|
299
|
+
});
|
|
300
|
+
|
|
301
|
+
it("should target the request or all of its variants", () => {
|
|
302
|
+
expect(optimistic(getTodos).remove(1).allVariants).toBeFalse();
|
|
303
|
+
expect(optimistic.all(getTodos).remove(1).allVariants).toBeTrue();
|
|
304
|
+
expect(optimistic.all(getTodos).remove(1).target).toBe(getTodos);
|
|
305
|
+
});
|
|
306
|
+
});
|
|
307
|
+
});
|