Skip to content

Instantly share code, notes, and snippets.

@evilUrge
Last active June 8, 2022 14:28
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save evilUrge/23b861b84ef19d8f547043cbb9952071 to your computer and use it in GitHub Desktop.
Aws SDK Paginator
/**
* Paginates over a AWS service function.
* @param functionToExec The function to execute
* @param methodToExec The method to execute
* @param params The parameters to pass to the method
* @param keyToAppend The key to append to the result
* @returns A promise that resolves to an array of results
*/
export async function paginator(
functionToExec: any,
methodToExec: string,
params: object,
keyToAppend: string,
): Promise<any[]> {
let NextToken = "",
nextToken = "",
pages: any = [];
do {
pages = pages.concat(
await functionToExec[methodToExec](Object.assign(params, NextToken && { NextToken }, nextToken && { nextToken }))
.promise()
.then((response: { [x: string]: any; NextToken: any }) => {
NextToken = response.NextToken;
nextToken = response.nextToken; // Legacy AWS SDK support.
return response[keyToAppend] || [];
})
.catch((error: any) => {
throw new Error(error.message);
})
);
} while (NextToken || nextToken);
return Promise.allSettled(pages).then((values) => {
if (values.find((i) => i.status === "rejected"))
throw new Error(
`Error in paginator: ${values
.filter((i) => i.status === "rejected")
.map((i) => Object.values(i).join(" - "))
.join("\n")}`
);
return values
.map((item: any) => item.value || item)
.flat()
.filter(Boolean);
});
}
@evilUrge
Copy link
Author

Paginate over any AWS SDK service object!

ex.

paginator(glue, "getDatabases", { MaxResults:100, ResourceShareType: "ALL" }, "DatabaseList")

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment