[Lab] DymamoDB Pagination
If you send a GET
request using this URL: https://{{apiId}}.execute-api.us-east-1.amazonaws.com/dev/groups?limit=2
you should get a reply like this:
{
"items": [
...
],
"nextKey": "%7B%22id%22%3A%221%22%7D"
}
Notice that you need to replace {{apiId}}
with an id of the API that you've deployed.
If you pass the nextKey
and use it with another GET
request using this URL: https://{{apiId}}.execute-api.us-east-1.amazonaws.com/dev/groups?limit=2&nextKey=%7B%22id%22%3A%221%22%7D
{
"items": [
...
],
"nextKey": null
}
If nextKey
is null
it means that there are no more items to return.
Notice that the value of the LastEvaluatedKey
in a DynamoDB result is a JSON object. To pass it in another GET request we convert it to a string and then use URI encoding to allow to pass it in a URL:
encodeURIComponent(JSON.stringify(lastEvaluatedKey))
To pass a value coming in a GET request you would need to first decode a string and then parse a JSON string:
// Value read from a query parameter
const nextKeyStr = ...
// "exclusiveStartKey" can be passed a parameter to a "scan()" call
const exclusiveStartKey = JSON.parse(decodeURIComponent(nextKeyStr))
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 | 'use strict' const AWS = require( 'aws-sdk' ) const docClient = new AWS.DynamoDB.DocumentClient() const groupsTable = process.env.GROUPS_TABLE exports.handler = async (event) => { console.log( 'Processing event: ' , event) let nextKey // Next key to continue scan operation if necessary let limit // Maximum number of elements to return try { // Parse query parameters nextKey = parseNextKeyParameter(event) limit = parseLimitParameter(event) || 20 } catch (e) { console.log( 'Failed to parse query parameters: ' , e.message) return { statusCode: 400, headers: { 'Access-Control-Allow-Origin' : '*' }, body: JSON.stringify({ error: 'Invalid parameters' }) } } // Scan operation parameters const scanParams = { TableName: groupsTable, Limit: limit, ExclusiveStartKey: nextKey } console.log( 'Scan params: ' , scanParams) const result = await docClient.scan(scanParams).promise() const items = result.Items console.log( 'Result: ' , result) // Return result return { statusCode: 200, headers: { 'Access-Control-Allow-Origin' : '*' }, body: JSON.stringify({ items, // Encode the JSON object so a client can return it in a URL as is nextKey: encodeNextKey(result.LastEvaluatedKey) }) } } /** * Get value of the limit parameter. * * @param {Object} event HTTP event passed to a Lambda function * * @returns {number} parsed "limit" parameter */ function parseLimitParameter(event) { const limitStr = getQueryParameter(event, 'limit' ) if (!limitStr) { return undefined } const limit = parseInt(limitStr, 10) if (limit <= 0) { throw new Error( 'Limit should be positive' ) } return limit } /** * Get value of the limit parameter. * * @param {Object} event HTTP event passed to a Lambda function * * @returns {Object} parsed "nextKey" parameter */ function parseNextKeyParameter(event) { const nextKeyStr = getQueryParameter(event, 'nextKey' ) if (!nextKeyStr) { return undefined } const uriDecoded = decodeURIComponent(nextKeyStr) return JSON.parse(uriDecoded) } /** * Get a query parameter or return "undefined" * * @param {Object} event HTTP event passed to a Lambda function * @param {string} name a name of a query parameter to return * * @returns {string} a value of a query parameter value or "undefined" if a parameter is not defined */ function getQueryParameter(event, name) { const queryParams = event.queryStringParameters if (!queryParams) { return undefined } return queryParams[name] } /** * Encode last evaluated key using * * @param {Object} lastEvaluatedKey a JS object that represents last evaluated key * * @return {string} URI encoded last evaluated key */ function encodeNextKey(lastEvaluatedKey) { if (!lastEvaluatedKey) { return null } return encodeURIComponent(JSON.stringify(lastEvaluatedKey)) } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
2020-05-02 [React Testing] Error State with React Testing Library, findBy*
2020-05-02 [React Testing] Use Generated Data in Tests with tests-data-bot to Improve Test Maintainability
2020-05-02 [React Testing] Test Drive Assertions with Dates in React
2020-05-02 [React Testing] Test Drive Mocking react-router’s Redirect Component on a Form Submission
2019-05-02 [Vuex] Add options to a Vuex plugin using TypeScript
2019-05-02 [Vuex] Write a Vuex Plugin using TypeScript
2018-05-02 [React] Refactor componentWillReceiveProps() to getDerivedStateFromProps() in React 16.3