How to close a database connection in a lambda function?

In my lambda function, I tried closing the mongo connection as soon as I send the callback. But this is a problem.

  • When I submit a request, the function performs its duties, sends a callback and closes the database connection.
  • When sending a second request, the function is disabled.
  • When I delete db.close(), everything works fine.

I think lambda reuses the connection for all functions, because I open the connection at the top of the handler:

// Connect to database
mongoose.connect(process.env.DATABASE_URL);


const handleCreateUser = async (event, context, callback) => {
  // eslint-disable-next-line no-param-reassign
  context.callbackWaitsForEmptyEventLoop = false;

  const data = JSON.parse(event.body);
  const { user, userProfile } = data;

  await createUser({ callback, user, userProfile });
};

Any idea how to fix this? Do we really need to close the connection at this point?

+4
source share
3 answers

mongoose.connect , db.close(). , Lambda, .

+3

, Mark mongoose.connect() , , . , . , , / , , ( , - , , , ). promises, , , . , . , , , , , , .

pg-pool postgres DB Lambda. - https://www.npmjs.com/package/pg-pool

0

Perhaps try try-with-resource , which automatically closes the connection.

-2
source

Source: https://habr.com/ru/post/1684170/


All Articles