So, MongoDB Data API only supports server apps and not browser app .In order to use it you have to implement another API in front of it to access it.
I wanted to learn and use AWS services ,so I thought of using AWS Lambda and API Gateway to create the APIs.
Create a MockAPI using AWS Lambda function and API Gateway and test it in Postman.
AWS Lambda
1. Created createInvoice function by connecting it to MongoDB database and using InsertOne function of MongoDB, to add data to the collection
const result = await db.collection("Invoices").insertOne(JSON.parse(event.body));
2. Created getSingleInvoice function and used find function of MongoDB, to find the requested Invoice based on path parameter InvoiceID in the API route.
//Get the parameter invoiceID from the event to find the invoice from the DB
var invoiceID = event.pathParameters.invoiceID;
const invoice = await db.collection("Invoices").find({ "_id": new ObjectID(invoiceID) }).toArray();
3. Created getAllInvoices function ,to get all the invoices from the DB
const invoice = await db.collection("Invoices").find({}).toArray();
AWS API Gateway
1. Create API
2. Select HTTP API which has CORS support in it and Build it
3. Add API Name and in Add Integrations ,add Lambda functions that you created
4. Configure routes select HTTP route method and route path based on what your function will be doing
5. Configure Access-Control-Allow-Origin to * i.e. ALL
API implementation code:
0 comments:
Post a Comment