Skip to content

Commit 9a51aad

Browse files
authored
fix(types): correct pagination return type for data which is an array (#662)
* fix(types): correct pagination return type for data which is an array Instead of returning `T` in `GetPaginationKeys<T>`, we return an empty object, because T would be an `OctokitResponse<T, S>`, and there is no response data in the `data` field Fixes #661 * test: add test for array response pagination * style: prettier
1 parent 8b8c500 commit 9a51aad

File tree

2 files changed

+22
-12
lines changed

2 files changed

+22
-12
lines changed

src/types.ts

+8-12
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,11 @@ import type { PaginatingEndpoints } from "./generated/paginating-endpoints.js";
2828
// : never
2929
// : never;
3030

31+
type PaginationMetadataKeys =
32+
| "repository_selection"
33+
| "total_count"
34+
| "incomplete_results";
35+
3136
// https://stackoverflow.com/a/58980331/206879
3237
type KnownKeys<T> = Extract<
3338
{
@@ -36,10 +41,7 @@ type KnownKeys<T> = Extract<
3641
? U
3742
: never,
3843
// Exclude keys that are known to not contain the data
39-
Exclude<
40-
keyof T,
41-
"repository_selection" | "total_count" | "incomplete_results"
42-
>
44+
Exclude<keyof T, PaginationMetadataKeys>
4345
>;
4446
type KeysMatching<T, V> = {
4547
[K in keyof T]: T[K] extends V ? K : never;
@@ -56,15 +58,9 @@ type GetResultsType<T> = T extends { data: any[] }
5658

5759
// Extract the pagination keys from the response object in order to return them alongside the paginated results
5860
type GetPaginationKeys<T> = T extends { data: any[] }
59-
? T
61+
? {}
6062
: T extends { data: object }
61-
? Pick<
62-
T["data"],
63-
Extract<
64-
keyof T["data"],
65-
"repository_selection" | "total_count" | "incomplete_results"
66-
>
67-
>
63+
? Pick<T["data"], Extract<keyof T["data"], PaginationMetadataKeys>>
6864
: never;
6965

7066
// Ensure that the type always returns the paginated results and not a mix of paginated results and the response object

test/validate-typescript.ts

+14
Original file line numberDiff line numberDiff line change
@@ -195,6 +195,20 @@ export async function requestMethodWithNamespacedResponse() {
195195
}
196196
}
197197

198+
// https://github.com/octokit/plugin-paginate-rest.js/issues/661
199+
// Ensure the endpoints that return an array don't have an extra `OctokitResponse` in the data
200+
type Package =
201+
PaginatingEndpoints["GET /orgs/{org}/packages/{package_type}/{package_name}/versions"]["response"]["data"][0];
202+
export async function requestWithArrayResponse() {
203+
const results = await octokit.paginate(
204+
"GET /orgs/{org}/packages/{package_type}/{package_name}/versions",
205+
);
206+
for (const result of results) {
207+
const pkg: Package = result;
208+
console.log(pkg.name);
209+
}
210+
}
211+
198212
export async function paginatingEndpointKeyProvidedByUser<
199213
R extends keyof PaginatingEndpoints,
200214
>(route: R) {

0 commit comments

Comments
 (0)