外部函数未在lambdaNode jsexports.handler中调用



在lambda中,当我们编写node js脚本时,是否可以在exports.handler之外运行函数?

例如:

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

若我需要在lambda中运行index.js,它只在exports.handler的函数内部执行。它不执行";主";CCD_ 3之外的函数。请帮助

从你的问题和评论中,听起来你正在寻找一种运行函数连接MongoDB的方法,但不是每次调用lambda函数时都重新运行连接。

解决此问题的一种方法是将数据库连接缓存在外部作用域中的一个变量中。

// 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;
};

最新更新