Monday, 24 April 2017

nodejs: How to nicely import constants?

I have one file with constant definitions (common.js):

var Errors = Object.freeze({
    SUCCESS: {code: 0, message: 'Success'},
    NOT_ENOUGH_ARGUMENTS: {code: 1, message: 'Not enough arguments provided'},
    NOT_ALLOWED_ARGUMENT: {code: 2, message: 'Argument value is not allowed'}
});

module.exports = Errors;

And another file that uses this one (profile.js):

var Errors = require('../../common');

module.exports.profileCreate = function (req, res) {
    var name = req.query.name;
    var email = req.query.email;

    if (!name || !email) {
        res
            .status(403)
            .json({error: Errors.NOT_ENOUGH_ARGUMENTS});
        return;
    }

    // ...
}

It looks to me that module.exports in first file and var Errors=require() in second one are having excessive syntax. Moreover I don't know what to do if I'd like to make some more enum constants instead of single Errors object.

What I have to do in order to use my enum object in other files of the project? Should I write down a bunch of exports for every enum object in the future, like:

module.exports.Errors = Object.freeze({ ... });
module.exports.Result = Object.freeze({ ... });
// ...etc



via meps

No comments:

Post a Comment