Created
May 27, 2020 11:53
-
-
Save tatat/1f0522d515586c0f2210356748dfd33f to your computer and use it in GitHub Desktop.
This file contains hidden or 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' | |
export const fetch = async (startKey?: AWS.DynamoDB.Key | undefined) => { | |
const ddb = new AWS.DynamoDB({ | |
endpoint: 'http://localhost:8000' | |
}) | |
const limit = 6 | |
const defaultInput: AWS.DynamoDB.ScanInput = { | |
TableName: 'ScanSample', | |
FilterExpression: '#number = :number', | |
ExpressionAttributeNames: { | |
'#number': 'number', | |
}, | |
ExpressionAttributeValues: AWS.DynamoDB.Converter.marshall({ | |
':number': 2, | |
}), | |
} | |
const responseCount = await ddb.scan({ | |
...defaultInput, | |
Select: 'COUNT', | |
}).promise() | |
const result: { | |
items: any[]; | |
key: AWS.DynamoDB.Key | undefined; | |
} = { | |
items: [], | |
key: undefined, | |
} | |
const fetchItems = async (key: AWS.DynamoDB.Key | undefined) => { | |
const response = await ddb.scan({ | |
...defaultInput, | |
Limit: limit, | |
ExclusiveStartKey: key, | |
}).promise() | |
result.items.push(...(response.Items?.map(item => AWS.DynamoDB.Converter.unmarshall(item)) ?? [])) | |
if (result.items.length > limit) { | |
result.items.splice(limit) | |
const keyItem = result.items[result.items.length - 1] | |
result.key = { | |
id: { | |
S: keyItem.id, | |
}, | |
ts: { | |
N: String(keyItem.ts), | |
}, | |
} | |
} else if (response.LastEvaluatedKey) { | |
return fetchItems(response.LastEvaluatedKey) | |
} | |
} | |
await fetchItems(startKey) | |
return { | |
items: result.items, | |
next: result.key ? Buffer.from(JSON.stringify(result.key)).toString('base64') : null, | |
count: result.items.length, | |
total: responseCount.Count, | |
} | |
} | |
const key = process.argv[2] ? JSON.parse(Buffer.from(process.argv[2], 'base64').toString()) : undefined | |
fetch(key).then(data => { | |
console.log(JSON.stringify(data)) | |
}).catch(error => { | |
console.error(error) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment