2016-10-10 6 views
-1

私はNode.jsを使い慣れていて、いくつかのクエストを持っています。私は簡単なチャットアプリを実装しており、ordjではExpressJS + Nodejs + Sockert.ioバンドルを使用しています。ここ はモジュールのエクスポート。 Node.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; 

は、それが許容可能なエクスポートオブジェクトのインスタンスである私のUserServive.jsありますか?それとも私は、このコードのように、すべてのmethidsは、静的にする必要があります。

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; 

答えて

0

それが唯一のサービスだとあなたがthisまたはあなただけのクラスの振る舞いを省略し、オブジェクトのみをエクスポートすることができるものとプレイする必要はありません。

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); 
     }); 
    } 
}; 
0

Node.js開発者は、グローバルスコープに物を置くのが嫌いです。これは私がそれを行う方法の例です:

module.exports = function() { 
    class MyClass { 
     // Stuff 
    } 

    return MyClass; 
} 

は、次にメインのファイルに:

const MyClass = require("./MyClass.js")(); 
+0

あなたの答えFOありがとう!私はそれを心に留めておきます。 –

0

あなたが実際にあなたのUserServiceの中で行うことができます。

export default UserService; 

そして

import UserService from './userService'; 
new UserService() 
関連する問題