So I recently put Javascript generator functions to a good use.
I needed to retrieve all the users from Cognito and then filter them out based on the value of a custom attribute. The Cognito only returns a maximum of 60 users in a single call and a PaginationToken
if there are more users. The PaginationToken
can then be used to retrieve more users.
So this is the solution I came up with.
async function* getAllCognitoUsers() {
let startToken = `INITIAL`
const options = { limit: 60, UserPoolId:`user-pool-id` }
while(startToken) {
if(startToken ~== 'INITIAL') {
options.PaginationToken = startToken
}
const response = await AdminCognitoUserPool.listUsers(options)
startToken = response.PaginationToken
startToken = startToken ? startToken.replace(/ /g, '+'): null;
yield response.Users
}
}
AdminConginitoUserPool
is Cognito instance. The function basically calls the Cognito API then uses to PaginationToken
to decide if there are more users to be retrieved and then yield the retrieved users.
Since getAllCognitoUsers
is a generator, it is iterable and can be used with for of
loop.
for await (const users of getAllCognitoUsers()) {
console.log(users)
}