Mor*_*ris 5 javascript node.js sequelize.js
当我以下列方式创建新模型时:
//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]
}
}
});
};
Run Code Online (Sandbox Code Playgroud)
并进入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;
Run Code Online (Sandbox Code Playgroud)
我不明白user.js如何知道sequelize(我作为参数插入module.exports)是sequelize包的实例,如果它位于另一个文件中?也许因为sequelize.import('/user.js')它导入了整个续集包?
看到的定义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];
};
Run Code Online (Sandbox Code Playgroud)
实际上,它调用require路径,然后使用sequelize实例作为其第一个参数调用结果.这就是结点,允许模块引用导入它的续集实例.
| 归档时间: |
|
| 查看次数: |
12604 次 |
| 最近记录: |