Last active
June 8, 2022 14:28
-
-
Save evilUrge/23b861b84ef19d8f547043cbb9952071 to your computer and use it in GitHub Desktop.
Aws SDK Paginator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Paginate over any AWS SDK service object!
ex.