繁体   English   中英

Node.js:组织我的应用程序:在单独的文件中使用路由和模型,如何从路由中获取模型?

[英]Node.js : organising my application : using routes and models in separate files, how can I get models from routes?

我是node.js(和javascript)的新手,并且正在关注有关如何为应用程序获取良好结构的教程。

首先,我想将路线保存在单独的文件夹中。

假设这是我的main.js:

var express = require('express');

const PORT = 3000;
const app = express();

app.set("json spaces", 2);

require('./routes')(app);

app.listen(PORT, function() {
   console.log(`users-jwt-api - Port ${PORT}`)
});

在我的“ routes”文件夹中,我有两个文件:用于加载其他文件的index.js和user.js

index.js:

var fs = require('fs');

module.exports = function(app){
   fs.readdirSync(__dirname).forEach(function(file) {
      if (file == "index.js") return;
      var name = file.substr(0, file.indexOf('.'));
      require('./' + name)(app);
   });
}

user.js:

module.exports = function(app) {
   app.get('/users', function(req, res) {
      //no bd yet, returning static data, and dont want it here, but in a model
      res.json({users:[{username: "titi", password:"toto"},{username: "tata", password:"tutu"}]});
   });
};

这就像一个魅力! 精细。

但是,要明确一点,我不希望路由文件中包含任何数据库代码,因此我尝试添加“模型”文件夹。 我将index.js放在其中,就像路由一样,在其中放入了users.js:

module.exports = function(app) {
   return {
      findAll: function(params, callback) {
         //no db yet
         return callback([{username: "titi", password:"toto"},{username: "tata", password:"tutu"}]);
      }
   };
};

我在路由之前添加了main.js来修改它:

require('./models')(app);

问题是,我不知道如何修改我的route / user.js来调用此模型!

我想在route / users.js中有这样的内容:

module.exports = function(app) {
   const Users = app.models.users; // not working here : TypeError: Cannot read property 'users' of undefined
   app.get('/users', function(req, res) {
      Users.findAll({}, function(users) {
         res.json({users: users});
      });
   });
};

如何通过app var使用我的模型?

注意:我找到了一个名为“ config”的模块用于依赖项注入的解决方案,但是在使用这种功能强大的快捷方式之前,我宁愿使用简单的编码。

任何帮助表示赞赏! 谢谢 !

如果您想访问models ,则需要将其定义为app上的属性,这就是models.js的工作。 您正在将应用程序传递给models.js但根本没有更改。

我建议更改models.js使其更像这样:

module.exports = function(app) {
   app.models = {
     users : // import db and return users so routes can avail of them
   };
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM