Amazon Dynamodb Query Lambda Function and Rest Api Connection
07-10-2020Amazon Dynamodb Lambda Function for Rest Api
Firstly install aws sdk package:npm i aws-sdk
Note: AWS Lambda now supports layers, we can easily create our library. For more information: https://medium.com/@anjanava.biswas/nodejs-runtime-environment-with-aws-lambda-layers-f3914613e20e
const config = require('./config.js');
const AWS = require('aws-sdk');
// Set the region
AWS.config.update(config.aws_remote_config);
// Create the DynamoDB service object
const db = new AWS.DynamoDB({apiVersion: 'latest'});
exports.handler = async (event) => {
let type = 'CURRENCY';
if (event !== undefined && event.type != null) type = event.type;
var params = {
TableName: config.aws_table_name,
FilterExpression: 'contains (#Type, :post)',
ExpressionAttributeNames: {
"#Type": "Type",
},
ExpressionAttributeValues: {
":post": {S: type}
}
};
const awsRequest = await db.scan(params);
try {
const result = await awsRequest.promise();
return {
statusCode: 200,
body: result.Items
};
} catch (e) {
return {
statusCode: 500,
body: e.code+": "+e.message
};
}
}
config.js file
module.exports = {
aws_table_name: 'Currencies',
aws_local_config: {
//Provide details for local configuration
},
aws_remote_config: {
accessKeyId: 'AKIAT6QDYTERBB3JQCD1',
secretAccessKey: 't0ZIzMu1BxqQJc4DjGkotffnp0Si/MxMsAIsWnxY',
region: 'us-east-1',
}
};
Create rest api in amazon aws then use lambda function described above. For more information: https://docs.aws.amazon.com/apigateway/latest/developerguide/rest-api-develop.html