通过将 express 'app' 传递给辅助方法,我们可以收集所有模型和控制器,并将它们分别添加到 app.models 和 app.controllers 对象中。我们也会遍历路线,但不需要存储它们。
目录结构:
myApplication
|__ src
| |__ controllers
| |__ Account.js
| index.js
| User.js
| models
| |__ Account.js
| index.js
| User.js
| routes
| |__ account.js
| index.js
| user.js
|
|__ node_modules
|__ package.json
|__
|__
|__
|
|__ server.js
我们使用 index.js 文件作为我们的辅助方法。这些方法只是遍历目录中的所有 js 文件(index.js 除外)并需要它们。
// controllers/index.js
var fs = require('fs');
var path = require('path');
module.exports = function(app) {
app.controllers = {};
fs.readdirSync(__dirname).forEach(function(f) {
if (f !== "index.js" && path.extname(f) === '.js'){
var controller = require(path.join(__dirname,f))(app);
app.controllers[controller.name] = controller;
}
});
};
// models/index.js
var fs = require('fs');
var path = require('path');
module.exports = function(app) {
app.models = {};
fs.readdirSync(__dirname).forEach(function(f) {
if (f !== "index.js" && path.extname(f) === '.js'){
var model = require(path.join(__dirname,f))(app);
app.models[model.modelName] = model;
}
});
};
// routes/index.js
var fs = require('fs');
var path = require('path');
module.exports = function (app) {
fs.readdirSync(__dirname).forEach(function(file) {
if (file !== "index.js" && path.extname(file) === '.js'){
require(path.join(__dirname, file))(app);
}
});
};
示例模型、控制器和路由:
// models/Account.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
module.exports = function(){
var AccountSchema = new Schema({
number : {type : String, required: true},
owner: {type: Schema.Types.ObjectId, ref: 'User'}
});
return mongoose.model("Account", AccountSchema); //'Account' is used to access this model as app.models.Account
};
// controllers/Account.js
module.exports = function(app) {
var Account = app.models.Account;
var Controller = {
name: 'Account' //this name is used to access this controller in routes as app.controllers.Account
};
// POST method to create user account
Controller.createAccount = function(req, res) {
Account.create(req.body, function(err, result){
if(err){
res.status(500).send("Server Error")
}
else{
res.send({message: "account created"});
}
})
};
return Controller;
};
// routes/account.js
module.exports = function (app) {
var AccountController = app.controllers.Account;
app.post('/api/accounts', AccountController.createAccount);
};
在 server.js 中:
var express = require('express');
var app = express();
.
.
.
. // server configurations
.
.
.
// maintain the below order:
require("./src/models")(app); // call the method in /src/models/index.js and pass express app
require("./src/controllers")(app);
require("./src/routes")(app);
你不会在模型、控制器或路由中添加一个空的 js 文件,因为它会通过错误。