-
Notifications
You must be signed in to change notification settings - Fork 20
/
iterator.ts
58 lines (50 loc) · 1.67 KB
/
iterator.ts
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
import type { Octokit } from "@octokit/core";
import { normalizePaginatedListResponse } from "./normalize-paginated-list-response";
import type {
EndpointOptions,
RequestInterface,
RequestParameters,
Route,
} from "./types";
export function iterator(
octokit: Octokit,
route: Route | RequestInterface,
parameters?: RequestParameters
) {
const options =
typeof route === "function"
? route.endpoint(parameters as EndpointOptions)
: octokit.request.endpoint(route, parameters);
const requestMethod = typeof route === "function" ? route : octokit.request;
const method = options.method;
const headers = options.headers;
let url = options.url;
return {
[Symbol.asyncIterator]: () => ({
async next() {
if (!url) return { done: true };
try {
const response = await requestMethod({ method, url, headers });
const normalizedResponse = normalizePaginatedListResponse(response);
// `response.headers.link` format:
// '<https://api.github.com/users/aseemk/followers?page=2>; rel="next", <https://api.github.com/users/aseemk/followers?page=2>; rel="last"'
// sets `url` to undefined if "next" URL is not present or `link` header is not set
url = ((normalizedResponse.headers.link || "").match(
/<([^>]+)>;\s*rel="next"/
) || [])[1];
return { value: normalizedResponse };
} catch (error: any) {
if (error.status !== 409) throw error;
url = "";
return {
value: {
status: 200,
headers: {},
data: [],
},
};
}
},
}),
};
}