2016-11-16 9 views
1

の作業方法:sequelize.import() - 私は次のようにnuewモデルを作成するとき、それは

//user.js file 
module.exports = function (sequelize, DateTypes) { 

return sequelize.define("user", { 
    email: { 
     type: DateTypes.STRING, 
     allowNull: false, 
     unique: true, 
     validate: { 
      isEmail: true 
     } 
    }, 
    password: { 
     type: DateTypes.STRING, 
     allowNull: false, 
     validate: { 
      len: [7, 100] 
     } 
    } 
}); 
}; 

と私は、新しいデータベースを構築しdb.jsファイルに:

var Sequelize = require('sequelize'); 
var env = process.env.NODE_ENV || "development"; // established if you work in production or in development mode 
var sequelize; 

if (env == "production") { 

    sequelize = new Sequelize(process.env.DATABASE_URL, { 
     "dialect": "postgres", 

    }); 
} else { 
    var sequelize = new Sequelize(undefined, undefined, undefined, { 
     'dialect': 'sqlite', 
     'storage': __dirname + '/data/dev-todo-api.sqlite' // location where you create a new sqlite database 
    }); 
} 

var db = {}; 

db.todo = sequelize.import(__dirname + "/models/todo.js"); 
db.user = sequelize.import(__dirname + "/models/user.js"); 
db.sequelize = sequelize; //contain a settings of database 
db.Sequelize = Sequelize; 

module.exports = db; 

私はこのことを理解していません:user.jsに "sequelize"(どのようにパラメータを "module.exports"に挿入したか)を知っている方法は、別のファイルに配置されている場合、パッケージを継承することですか?たぶん "sequelize.import(/user.js)"で、それはsequelizeパッケージ全体をインポートするでしょうか?

おかげで、すべての モリス

答えて

2

sequelize.importの定義を参照してください:

Sequelize.prototype.import = function(path) { 
    // is it a relative path? 
    if(Path.normalize(path) !== Path.resolve(path)){ 
    // make path relative to the caller 
    var callerFilename = Utils.stack()[1].getFileName() 
     , callerPath = Path.dirname(callerFilename); 

    path = Path.resolve(callerPath, path); 
    } 

    if (!this.importCache[path]) { 
    var defineCall = (arguments.length > 1 ? arguments[1] : require(path)); 
    if (typeof defineCall === 'object' && defineCall.__esModule) { 
     // Babel/ES6 module compatability 
     defineCall = defineCall['default']; 
    } 
    this.importCache[path] = defineCall(this, DataTypes); 
    } 

    return this.importCache[path]; 
}; 

が効果的にそれがパスにrequireを呼び出し、その最初の引数としてsequelizeインスタンスで結果を呼び出します。これは結び目を結びつけて、モジュールがそれをインポートした後遺症のインスタンスへの参照を持つことを可能にします。

+0

次に、 "sequelize.import()"は、モデルをuser.jsに受信するために "require"を使用する方法ですが、 "sequelize.import()"のistance "sequelize"はパスファイルに渡されます。右? – DevWeb

+0

これは、 'require(path)(this、DataTypes)'が効果的に発生したときに起こります。 –

関連する問題