Home > Enterprise >  How to use function before initializing within module.exports
How to use function before initializing within module.exports

Time:01-29

I have two functions the first is register which uses a function called emailExists and both functions are exported using

// services.js
module.exports = {
async register(prm) { emailExists(prm) // emailExists is not defined  },
async emailExists(prm) { // do something } 
} 

I have a couple of questions should I use a class that contains all the methods in the services layer or that's not a best practice to use a class for the services layer or should I declare the functions and then exporting?

CodePudding user response:

You have various choices:

  • use the this keyword (doesn't work if the require()d module is destructed):

    module.exports = {
      async register(prm) { this.emailExists(prm) },
      async emailExists(prm) { /* do something */ },
    };
    
  • refer to the method as part of module.exports:

    module.exports = {
      async register(prm) { module.exports.emailExists(prm) },
      async emailExists(prm) { /* do something */ },
    };
    
  • declare local functions up-front, then export them:

    async function register(prm) { emailExists(prm) }
    async function emailExists(prm) { /* do something */ }
    module.exports = { register, emailExists };
    

No, you should not use a class unless you actually need multiple different instances.

  • Related