Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
serverlessExample-lambda-listCharacters.js
'use strict';
const AWS = require('aws-sdk');
const dynamoClient = new AWS.DynamoDB.DocumentClient({
region: 'us-east-1'
});
function buildResponse(dynamoData) {
console.log("dynamoData: " + JSON.stringify(dynamoData));
return dynamoData;
}
function responseHandler(statusCode, responsePayload, callback) {
const response = {
statusCode: 200,
headers: {
"Access-Control-Allow-Origin": "*", // Required for CORS support to work
"Access-Control-Allow-Credentials": true // Required for cookies, authorization headers with HTTPS
},
body: JSON.stringify(responsePayload)
};
console.log("responseHandler: " + JSON.stringify(response));
callback(null, response);
}
function buildQueryParams(classFilter, resultLimit, scanIndexForwardValue) {
var gameId = "1";
var queryParams = {
TableName: "characterData",
Limit: resultLimit,
ScanIndexForward: scanIndexForwardValue,
KeyConditionExpression: "#gameId = :gameId",
ExpressionAttributeNames: {
"#gameId": "gameId"
},
ExpressionAttributeValues: {
":gameId": gameId
}
}
console.log("buildQueryParams \n\n " + JSON.stringify(queryParams) + " \n\n");
return queryParams;
}
exports.handler = function(event, context, callback) {
console.log('Received event:', JSON.stringify(event, null, 2));
try {
// our HTTP query parameters
var sortField = event.queryStringParameters.sortfield;
var sortOrder = event.queryStringParameters.sortorder;
var classFilter = event.queryStringParameters.classfilter;
var resultLimit = event.queryStringParameters.resultLimit;
console.log("API Params: \
sortField: " + sortField + "\
sortOrder: " + sortOrder + "\
classFilter: " + classFilter + "\
");
// sort order
var scanIndexForwardValue = true;
if (sortOrder == "desc") {
scanIndexForwardValue = false;
}
var queryString = buildQueryParams(classFilter, resultLimit, scanIndexForwardValue);
// Get response
dynamoClient.query(queryString, function(err, itemData) {
if (err) {
responseHandler(500, err, callback);
} else {
responseHandler(200, buildResponse(itemData), callback);
}
});
} catch (ex) {
console.log("Error -- exports.handler: " + ex);
responseHandler(500, ex, callback);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment