0
\$\begingroup\$

The question is about nodejs module pattern code structure.

My goal is to initialise the module at one time and export the module using module.export so that, it's available in other files.

I took Twilio for explaining.

Here I want to initialize twilo using credentials and export it as twilioClient, which I can reuse without reinitialising. But I also need a dynamic Twilio client, ie, I give the credentials as params and create a client using that param.

That was my requirement and I came across this structure,

const twilio = require('twilio');


function init (config) {
    const twilioSID = config.TWILIO_ACCOUNT_SID;
    const twilioAuth = config.TWILIO_AUTH_TOKEN;
    const client = twilio(twilioSID, twilioAuth);
    return client;
}

const twilioSID = process.env.TWILIO_ACCOUNT_SID;
const twilioAuth = process.env.TWILIO_AUTH_TOKEN;
const client = twilio(twilioSID, twilioAuth);


module.exports = {
    twilioClient: client,
    twilioClientFn: init
};

Is this structure okay? is there any room for improvement? Thank You

\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

Keep it D.R.Y.

  • Avoid repeating code. The function init has its task repeated below it. There is no need to repeat that code, use the function.
  • Avoid single use variables. The function is storing values in variables for no reason. Use the references directly, return the result of the call twilio rather than store it before returning it.

Aim to keep the code short, more code is more to read understand and maintain. In this case less code also means less CPU cycles needed to run

Rewrite

Does the same in less than half the code.

const twilio = require("twilio");
const twilioClientFn = env => twilio(env.TWILIO_ACCOUNT_SID, env.TWILIO_AUTH_TOKEN);
module.exports = {
    twilioClient: twilioClientFn(process.env),
    twilioClientFn,
};
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.