I m having an issue with one of my AWS Lambda Node JS functions when I call the function from axios in my Next JS frontend. The first time the function is called, it is successful and returns correctly but when I call it again, it returns Error: Runtime exited with error: exit status 128 and ERROR Unhandled Promise Rejection Runtime.UnhandledPromiseRejection . When I call it again after a failed attempt, it runs successfully and returns correctly. Is there an issue with my code (below)? I ve got context.callbackWaitsForEmptyEventLoop set to false but I can t see why the function fails with rapid fire calls. Thanks in advance
const MongoClient = require("mongodb").MongoClient;
const ObjectId = require("mongodb").ObjectId;
const MONGODB_URI = process.env.MONGODB_URI;
let cachedDb = null;
async function connectToDatabase() {
if (cachedDb) {
return cachedDb;
}
const client = await MongoClient.connect(MONGODB_URI);
const db = await client.db(process.env.MONGODB_NAME);
cachedDb = db;
return db;
}
exports.handler = async (event, context) => {
console.log(event.queryStringParameters);
console.log(event.body);
let docType = event.queryStringParameters.docType;
let docId = event.queryStringParameters.docId;
const bodyData = JSON.parse(event.body);
let fundId = event.queryStringParameters.fundId;
context.callbackWaitsForEmptyEventLoop = false;
const db = await connectToDatabase();
try {
const data = await db.collection(docType).findOneAndUpdate({_id : ObjectId(docId), "profile_subscription_documents.fund_id" : fundId},{
$push: {"profile_subscription_documents.$[psd].profile_fund_subscription_documents": {...bodyData} }
},
{
arrayFilters: [
{
"psd.fund_id": fundId
}]
},
{
returnDocument: "after"
});
console.log("Here", data);
const response = {
statusCode: 200,
headers: {
"Access-Control-Allow-Headers" : "*",
"Access-Control-Allow-Origin": "http://localhost:3000/",
"Access-Control-Allow-Methods": "*"
},
body: JSON.stringify(data),
};
return response;
} catch (error) {
console.error(error);
}
};