shree
shree

Reputation: 2757

Outside function not calling in lambda node js exports.handler?

In lambda when we write node js script, is it possible to run a function outside of exports.handler?

For example:

// index.js

const main = async () => {

console.log(" running ");
};
main();
exports.handler = function(event, context) {
 const response = {
    statusCode: 200,
    body: JSON.stringify('done!'),
  };
return response;
};

If I need to run index.js in lambda, it is executing only inside function of exports.handler. Its not executing the "main" function which is outside of exports.handler. please help someone

Upvotes: 2

Views: 1148

Answers (1)

jasonandmonte
jasonandmonte

Reputation: 2028

From your question and comment it sounds like you are looking for a way to run a function to connect to MongoDB, but not rerun the connection every time the lambda function is called.

One method to resolve this is to cache the database connection in a variable in the outer scope.

// Store db after first connection
let cachedDb = null;
// database connection function
const main = async () => {
  // Guard clause to return cache
  if (cachedDb) return cachedDb;
  
  // Only creates the connection on the first function call
  const client = await MongoClient.connect('your connection URI')
  const db = await client.db('your database')
  cachedDb = db;
  
  return db;
};

exports.handler = async (event, context) => {
  const db = await main();
  // Add database interactions/queries
  // ...

  const response = {
    statusCode: 200,
    body: JSON.stringify('done!'),
  };
return response;
};

Upvotes: 2

Related Questions