Reputation: 285
If I don't close the DB connection at the end of my serverless function my script will hang and timeout.
I'm hoping there is a way I can run a clean up function at the end of any of my serverless functions which will close active DB connections etc.
module.exports.create = (event, context, callback) => {
user.insert({
//user details
}).then((results) => {
responseHelper.success(JSON.stringify(results), callback);
}, (error) => {
// Connection error
responseHelper.error(error, callback);
});
// I don't want to have this at the end of every function
// I'd rather run it in a cleanup step which runs on all functions
db.closeConnections();
}
Upvotes: 3
Views: 800
Reputation: 3993
First of all, user.insert()
returns a Promise and calling db.closeConnections()
right after it may close the connection when you still need it. To achieve what you want to do, db.closeConnections()
should be called just before the callback
parameter.
Maybe you could call db.closeConnections();
in your helper functions responseHelper.success()
and responseHelper.error()
, before the execution of the callback
parameter. I guess these functions are written only once and shared by all your lambda handler.
Upvotes: 1