Niaz Bibkaev Niaz Bibkaev - 1 month ago 8
Node.js Question

Module exports. Node.js

I'm new to Node.js and i have some questons. I'm implementing simple chat app and in ordor to do that I'm using ExpressJS + Nodejs + Sockert.io bundle.
Here is my UserServive.js

var db = require('../db')

class UserService {

findUserByNick(nick, callback) {
let userCollection = db.get('usercollection')
userCollection.findOne({username: nick}, (error, data) => {
callback(error, data);
});
}

findUserByEmail(email, callback) {
let userCollection = db.get('usercollection')
userCollection.findOne({email: nick}, (error, data) => {
callback(error, data);
});
}
}

var us = new UserService();
module.exports = us;


Is it acceptable export object instance? Or I should make all methids static like in this code:

class tokens_controller extends require('./controller_utils') {
static check_token(token_data, callback) {
if (this.validator(token_data, valid_templates.tokens.check_token, callback)) {
this.get_token_info(token_data.access_token, (get_token_info_err, get_token_info_result)=> {
TOKENS_MODEL.update({token: token_data.access_token}, (update_error, update_result)=> {
console.log(update_result);
if (update_error) {
callback(update_error, null);
}
else {
USERS_MODEL.find_users({
find: [{user_id: update_result.user_id}],
nots: ['password']
}, (find_users_error, find_users_result)=> {
if (find_users_error) {
callback(find_users_error, null);
}
else {
let user = find_users_result[0];
let result = {user: user, token: update_result};
callback(null, result);
}

});
}
});
}, callback);

}
}
}
module.exports = tokens_controller;

Answer

If it's only a service and you don't need to play with this or something you can just omit the class behavior and only export an object.

var db = require('../db')

module.exports = {

    findUserByNick: function(nick, callback) {
        let userCollection = db.get('usercollection')
        userCollection.findOne({username: nick}, (error, data) => {
            callback(error, data);
        });
    },

    findUserByEmail: function(email, callback) {
        let userCollection = db.get('usercollection')
        userCollection.findOne({email: nick}, (error, data) => {
            callback(error, data);
        });
    }
};
Comments