Repository navigation
Expand file tree
/
Copy pathstackApiV2.test.ts
More file actions
327 lines (284 loc) · 12.2 KB
/
Copy pathstackApiV2.test.ts
File metadata and controls
327 lines (284 loc) · 12.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
import { afterEach, describe, expect, it, vi } from "vitest";
import { StackApiV2Client } from "./stackApiV2";
afterEach(() => {
vi.unstubAllGlobals();
});
function responseWithJson(body: unknown): Response {
const response = new Response("", { status: 200 });
vi.spyOn(response, "json").mockResolvedValue(body);
return response;
}
describe("StackApiV2Client", () => {
it("fetches all pages and appends the team slug for Basic/Business", async () => {
const fetchMock = vi.fn()
.mockResolvedValueOnce(new Response(JSON.stringify({ items: [{ id: 1 }], has_more: true }), { status: 200 }))
.mockResolvedValueOnce(new Response(JSON.stringify({ items: [{ id: 2 }], has_more: false }), { status: 200 }));
const client = new StackApiV2Client({
apiV2Url: "https://api.stackoverflowteams.com/2.3",
teamSlug: "example-team",
headers: { "X-API-Access-Token": "token" },
fetchFn: fetchMock,
});
await expect(client.getPagedItems("/users", { pagesize: "100" })).resolves.toEqual([{ id: 1 }, { id: 2 }]);
expect(fetchMock.mock.calls[0][0].toString()).toContain("team=example-team");
expect(fetchMock.mock.calls[1][0].toString()).toContain("page=2");
});
it("waits for a backoff before requesting the next page without a throttle callback", async () => {
let releaseWait: (() => void) | undefined;
const waitFn = vi.fn(() => new Promise<void>((resolve) => {
releaseWait = resolve;
}));
const fetchMock = vi.fn()
.mockResolvedValueOnce(responseWithJson({
items: [{ id: 1 }],
has_more: true,
backoff: 3,
quota_remaining: 99,
}))
.mockResolvedValueOnce(responseWithJson({ items: [{ id: 2 }], has_more: false }));
const client = new StackApiV2Client({
apiV2Url: "https://api.stackoverflowteams.com/2.3",
teamSlug: "example-team",
fetchFn: fetchMock,
waitFn,
});
const result = client.getPagedItems("/users");
await vi.waitFor(() => expect(waitFn).toHaveBeenCalledWith(3));
expect(fetchMock).toHaveBeenCalledTimes(1);
releaseWait?.();
await expect(result).resolves.toEqual([{ id: 1 }, { id: 2 }]);
expect(fetchMock).toHaveBeenCalledTimes(2);
});
it("notifies, waits once, and then requests the next page", async () => {
const events: string[] = [];
const fetchMock = vi.fn(async () => {
const page = fetchMock.mock.calls.length;
events.push(`fetch-${page}`);
return page === 1
? responseWithJson({ items: [{ id: 1 }], has_more: true, backoff: 4, quota_remaining: 12 })
: responseWithJson({ items: [{ id: 2 }], has_more: false });
});
const onThrottle = vi.fn(async () => {
events.push("notify");
});
const waitFn = vi.fn(async () => {
events.push("wait");
});
const client = new StackApiV2Client({
apiV2Url: "https://api.stackoverflowteams.com/2.3",
teamSlug: "example-team",
fetchFn: fetchMock,
onThrottle,
waitFn,
});
await expect(client.getPagedItems("/users")).resolves.toEqual([{ id: 1 }, { id: 2 }]);
expect(onThrottle).toHaveBeenCalledTimes(1);
expect(onThrottle).toHaveBeenCalledWith({ kind: "backoff", seconds: 4, remaining: 12 });
expect(waitFn).toHaveBeenCalledTimes(1);
expect(waitFn).toHaveBeenCalledWith(4);
expect(events).toEqual(["fetch-1", "notify", "wait", "fetch-2"]);
});
it("carries a terminal-page backoff to the next call and consumes it once", async () => {
let releaseWait: (() => void) | undefined;
const waitFn = vi.fn(() => new Promise<void>((resolve) => {
releaseWait = resolve;
}));
const onThrottle = vi.fn(async () => undefined);
const fetchMock = vi.fn()
.mockResolvedValueOnce(responseWithJson({
items: [{ id: 1 }],
has_more: false,
backoff: 5,
quota_remaining: 8,
}))
.mockResolvedValueOnce(responseWithJson({ items: [{ id: 2 }], has_more: false }))
.mockResolvedValueOnce(responseWithJson({ items: [{ id: 3 }], has_more: false }));
const client = new StackApiV2Client({
apiV2Url: "https://api.stackoverflowteams.com/2.3",
teamSlug: "example-team",
fetchFn: fetchMock,
onThrottle,
waitFn,
});
await expect(client.getPagedItems("/users")).resolves.toEqual([{ id: 1 }]);
expect(onThrottle).toHaveBeenCalledTimes(1);
expect(onThrottle).toHaveBeenCalledWith({ kind: "backoff", seconds: 5, remaining: 8 });
expect(waitFn).not.toHaveBeenCalled();
const secondResult = client.getPagedItems("/tags");
await vi.waitFor(() => expect(waitFn).toHaveBeenCalledWith(5));
expect(fetchMock).toHaveBeenCalledTimes(1);
releaseWait?.();
await expect(secondResult).resolves.toEqual([{ id: 2 }]);
await expect(client.getPagedItems("/badges")).resolves.toEqual([{ id: 3 }]);
expect(waitFn).toHaveBeenCalledTimes(1);
expect(onThrottle).toHaveBeenCalledTimes(1);
expect(fetchMock).toHaveBeenCalledTimes(3);
});
it("does not wait when a non-terminal page has no backoff", async () => {
const waitFn = vi.fn(async () => undefined);
const fetchMock = vi.fn()
.mockResolvedValueOnce(responseWithJson({ items: [{ id: 1 }], has_more: true }))
.mockResolvedValueOnce(responseWithJson({ items: [{ id: 2 }], has_more: false }));
const client = new StackApiV2Client({
apiV2Url: "https://api.stackoverflowteams.com/2.3",
teamSlug: "example-team",
fetchFn: fetchMock,
waitFn,
});
await client.getPagedItems("/users");
expect(waitFn).not.toHaveBeenCalled();
});
it("stops pagination at the requested max pages", async () => {
const fetchMock = vi.fn()
.mockResolvedValueOnce(new Response(JSON.stringify({ items: [{ id: 1 }], has_more: true }), { status: 200 }))
.mockResolvedValueOnce(new Response(JSON.stringify({ items: [{ id: 2 }], has_more: true }), { status: 200 }));
const client = new StackApiV2Client({
apiV2Url: "https://api.stackoverflowteams.com/2.3",
teamSlug: "example-team",
fetchFn: fetchMock,
});
await expect(client.getPagedItems("/users", { pagesize: "50" }, { maxPages: 1 })).resolves.toEqual([{ id: 1 }]);
expect(fetchMock).toHaveBeenCalledTimes(1);
});
it("fails closed when pagination exceeds the internal safety limit", async () => {
const fetchMock = vi.fn(async () =>
new Response(JSON.stringify({ items: [{ id: 1 }], has_more: true }), { status: 200 }));
const client = new StackApiV2Client({
apiV2Url: "https://api.stackoverflowteams.com/2.3",
teamSlug: "example-team",
fetchFn: fetchMock,
paginationSafetyLimit: 2,
});
await expect(client.getPagedItems("/tags")).rejects.toThrow(
"exceeded the internal safety limit of 2 pages. No complete result was produced.",
);
expect(fetchMock).toHaveBeenCalledTimes(2);
});
it("returns pagination metadata when max pages leaves more v2 data available", async () => {
const fetchMock = vi.fn().mockResolvedValueOnce(
new Response(JSON.stringify({ items: [{ id: 1 }], has_more: true }), { status: 200 }),
);
const client = new StackApiV2Client({
apiV2Url: "https://api.stackoverflowteams.com/2.3",
teamSlug: "example-team",
fetchFn: fetchMock,
});
await expect(client.getPagedResult("/users", { pagesize: "50" }, { maxPages: 1 })).resolves.toEqual({
items: [{ id: 1 }],
pageCount: 1,
reachedMaxPages: true,
hasMore: true,
});
expect(fetchMock).toHaveBeenCalledTimes(1);
});
it.each([
["a null body", null],
["an array body", []],
["missing items", { has_more: false }],
["non-array items", { items: {}, has_more: false }],
["missing has_more", { items: [] }],
["non-boolean has_more", { items: [], has_more: "false" }],
["inherited pagination fields", Object.create({ items: [], has_more: false })],
])("fails closed when page 1 has %s", async (_label, body) => {
const client = new StackApiV2Client({
apiV2Url: "https://api.stackoverflowteams.com/2.3",
teamSlug: "example-team",
fetchFn: vi.fn().mockResolvedValue(responseWithJson(body)),
});
await expect(client.getPagedItems("/users")).rejects.toThrow(
"Stack API v2.3 returned an invalid pagination envelope for /users page 1. No complete result was produced.",
);
});
it.each([
["a string backoff", { backoff: "2" }],
["a negative backoff", { backoff: -1 }],
["a fractional backoff", { backoff: 1.5 }],
["a non-finite backoff", { backoff: Number.NaN }],
["a negative quota", { quota_remaining: -1 }],
["a fractional quota", { quota_remaining: 1.5 }],
["a non-finite quota", { quota_remaining: Number.POSITIVE_INFINITY }],
])("fails closed when page 1 has %s", async (_label, optionalFields) => {
const client = new StackApiV2Client({
apiV2Url: "https://api.stackoverflowteams.com/2.3",
teamSlug: "example-team",
fetchFn: vi.fn().mockResolvedValue(responseWithJson({
items: [],
has_more: false,
...optionalFields,
})),
});
await expect(client.getPagedItems("/users")).rejects.toThrow(
"Stack API v2.3 returned an invalid pagination envelope for /users page 1. No complete result was produced.",
);
});
it("validates every v2 page before returning any accumulated result", async () => {
const fetchMock = vi.fn()
.mockResolvedValueOnce(responseWithJson({ items: [{ id: 1 }], has_more: true }))
.mockResolvedValueOnce(responseWithJson({ items: [{ id: 2 }] }));
const client = new StackApiV2Client({
apiV2Url: "https://api.stackoverflowteams.com/2.3",
teamSlug: "example-team",
fetchFn: fetchMock,
});
await expect(client.getPagedItems("/users")).rejects.toThrow(
"Stack API v2.3 returned an invalid pagination envelope for /users page 2. No complete result was produced.",
);
expect(fetchMock).toHaveBeenCalledTimes(2);
});
it("throws a mapped error on non-200 responses", async () => {
const fetchMock = vi.fn().mockResolvedValue(new Response("bad key", { status: 400 }));
const client = new StackApiV2Client({
apiV2Url: "https://demo.stackenterprise.co/api/2.3",
teamSlug: null,
headers: { "X-API-Key": "bad" },
fetchFn: fetchMock,
});
await expect(client.getPagedItems("/tags")).rejects.toThrow("Stack API v2.3 request failed with 400");
});
it("includes structured Stack API error details on non-200 responses", async () => {
const fetchMock = vi.fn().mockResolvedValue(
new Response(
JSON.stringify({
error_id: 403,
error_message: "`key` is not valid for passed `access_token`, application did not create token.",
error_name: "access_denied",
}),
{ status: 400 },
),
);
const client = new StackApiV2Client({
apiV2Url: "https://demo.stackenterprise.co/api/2.3",
teamSlug: null,
headers: { "X-API-Key": "bad" },
fetchFn: fetchMock,
});
await expect(client.getPagedItems("/tags")).rejects.toThrow(
"Stack API v2.3 request failed with 400: access_denied - `key` is not valid for passed `access_token`, application did not create token.",
);
});
it("throws a contextual error on invalid JSON responses", async () => {
const fetchMock = vi.fn().mockResolvedValue(new Response("not json", { status: 200 }));
const client = new StackApiV2Client({
apiV2Url: "https://demo.stackenterprise.co/api/2.3",
teamSlug: null,
fetchFn: fetchMock,
});
await expect(client.getPagedItems("/tags")).rejects.toThrow("Stack API v2.3 returned invalid JSON");
});
it("calls the default browser fetch with the global receiver", async () => {
const fetchMock = vi.fn(function (this: unknown) {
if (this !== globalThis) {
throw new TypeError("Illegal invocation");
}
return Promise.resolve(
new Response(JSON.stringify({ items: [{ id: 1 }], has_more: false }), { status: 200 }),
);
});
vi.stubGlobal("fetch", fetchMock);
const client = new StackApiV2Client({
apiV2Url: "https://api.stackoverflowteams.com/2.3",
teamSlug: "example-team",
});
await expect(client.getPagedItems("/users")).resolves.toEqual([{ id: 1 }]);
});
});