Last active
August 26, 2018 19:24
-
-
Save chrisorlandodev/f0b0cc1d053844f882bb1442c7a8986a to your computer and use it in GitHub Desktop.
Generator function to iterator over a DynamoDB Query/Scan
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
import * as AWS from 'aws-sdk' | |
import {DocumentClient} from "aws-sdk/lib/dynamodb/document_client"; | |
import QueryOutput = DocumentClient.QueryOutput; | |
import QueryInput = DocumentClient.QueryInput; | |
import ScanInput = DocumentClient.ScanInput; | |
import ScanOutput = DocumentClient.ScanOutput; | |
const dynamodb = new AWS.DynamoDB.DocumentClient(); | |
// polyfill | |
if (Symbol["asyncIterator"] === undefined) ((Symbol as any)["asyncIterator"]) = Symbol.for("asyncIterator"); | |
/** | |
* Iterate over the results of a DynamoDB Query or Scan | |
* | |
* @param {DocumentClient.QueryInput | DocumentClient.ScanInput} params | |
* @param {string} queryType | |
* @returns {Promise<DocumentClient.AttributeMap>} | |
*/ | |
export async function* queryIterator(params: QueryInput | ScanInput, queryType = 'query') { | |
while (true) { | |
let response = queryType === 'query' | |
? <QueryOutput> await dynamodb.query(params).promise() | |
: <ScanOutput> await dynamodb.scan(params).promise(); | |
if (response.Items) { | |
for (let item of response.Items) { | |
yield item; | |
} | |
} | |
if (!response.LastEvaluatedKey) return; | |
params.ExclusiveStartKey = response.LastEvaluatedKey; | |
} | |
} |
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
/** | |
* Helper function to build query params | |
* | |
* @returns {IterableIterator<DocumentClient.AttributeMap | undefined>} | |
*/ | |
export function activeUsers() { | |
let queryParams = <QueryInput> { | |
TableName: 'users', | |
IndexName: 'userType-terminatesAt-index', | |
KeyConditionExpression: 'userType = :userType AND terminatesAt > :now', | |
ExpressionAttributeValues: { | |
':userType': 'user', | |
':now': Date.now() | |
} | |
}; | |
return queryIterator(queryParams, 'query'); | |
} | |
(async() => { | |
for await(const user of activeUsers()) { | |
// Do something with the user | |
} | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment