Skip to content

Instantly share code, notes, and snippets.

@evilUrge
Last active Jun 8, 2022
Embed
What would you like to do?
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

evilUrge commented Dec 15, 2021

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