Q:

AWS NodeJS Lambda : pass event data object as parameter to a require module

I have a NodeJS 12 lambda function with three files : index.js, helpers.js, dbconfig.js
index.js
exports.handler = async function (event, context, callback) {
    context.callbackWaitsForEmptyEventLoop = false;

    const env = event.env;

    const id = event.userid;

    const helpers = require('./helpers');

    var userData = await helpers.getUserById(id);

    callback(null, userData);
};

helpers.js
const db = require('./dbconfig');

module.exports = {
    getUserById: async function (id) {
        const userIdData = await db.any('SELECT * FROM users WHERE id = $1', [id]);

        return userIdData;
    },

and finally dbconfig.js
const pgp = require('pg-promise')();

const cn = {
    user: 'dbuser',
    host: 'some-rds-instance.aws',
    database: 'db',
    password: 'pass',
    port: 5432,

    };
const db = pgp(cn);

module.exports = db;

Note : I have a bit simplified / reduce the code for the purpose of the question
The env value is the staging value retursn by the AWS API Gateway. It allows me to know if this is the development API Gateway calling or the production one. Two possible values : dev or prod
Goal :
Depending on the return value, i would like to pass it to the dbconfig module in order to set different database settings. Production settings when the env returns prod and development settings when the value is set to dev. Pretty straightforward
How to do this ?
First, i though of setting a db variable wich will require the db config with parameters like :
index.js
[...]
const env = event.env;

const db = require('./dbconfig')(env);

[...]
dbconfig.js
[...]
    module.export = function (env){
    if(env == 'prod)
      ....
   return  db;

[...]
But then db is now undefined in helpers.js :
const userIdData = await db.any('SELECT * FROM users WHERE id = $1', [id]);

I am a bit stuck. How i can pass the const env without refactoring all ?

A:

Ok, this was quite obvious (just kidding, i spent too much time on this)
In index.js, we can export the variable
exports.handler = async function (event, context, callback) {
    context.callbackWaitsForEmptyEventLoop = false;

    var env = event.env;
    module.exports = env;

then in dbconfig.js
const env = require('./index');
const pgp = require('pg-promise')();

if (env == 'dev') ...

The all thing was ... i didn't know that we can export from the index file.
And now i do :=)

