I am new to the serverless architecture design. Basically I wanted to read/update data from/to the mongodb database. To achieve this, I have created API Gateway with two resources ( list, update ) and created two lambda methods ( listFunction, updateFunction ).
Is there any way I can write in single lambda method and perform list/update based on the api gateway resource name?
2 Answers 2
Yes you can use single function to serve all your operations.
In api Gateway event you get the resource path and http method type.
So you can have if else block to handle the request based on path in your handler.
In your api Gateway configure both the methods with new lambda function.
Comments
To create a Lambda function that can perform CRUD operations on MongoDB, first make sure that you deploy a MongoDB instance to an EC2 instance as discussed here:
Install and configure MongoDB community edition
Once you verify that the MongoDB instance is succesfully deploy and running, now you can write a Lambda function that perform CRUD operations. I would write the Lambda function using the Lambda runtime Java API and then use the Mongo Java API to interact with a MongoDB collection.
For example, create a MongoClient instance in your Lambda function.
private String mongoUri = "mongodb://<ENTER EC2 IP Address>.amazonaws.com:27017" ;
private MongoClient getConnection() {
try {
MongoClient mongoClient = new MongoClient(new MongoClientURI(mongoUri));
return mongoClient;
} catch (Exception e) {
e.getStackTrace();
}
return null;
}
Now you can perform CRUD operations from within a Lambda Function.
If you want to use API Gateway, you can invoke this Lambda function using API Gateway.
Comments
Explore related questions
See similar questions with these tags.
contextandevent.proxy integrationas well astemplate mappingto get theresource namein the lambda.