简体   繁体   English

ExpressJS和Mongoose REST API结构:最佳实践?

[英]ExpressJS & Mongoose REST API structure: best practices?

I'm building a REST API with the use of NodeJS (Mongoose & ExpressJS). 我正在使用NodeJS(Mongoose和ExpressJS)构建REST API。 I think I have a pretty good basic structure at the moment, but I'm wondering what the best practices are for this kind of project. 我认为我目前有一个非常好的基本结构,但我想知道这种项目的最佳实践是什么。

In this basic version, everything passes through the app.js file. 在这个基本版本中,所有内容都通过app.js文件传递。 Every HTTP method is then passed to the resource that has been requested. 然后将每个HTTP方法传递给已请求的资源。 This allows me to dynamically add resources to the API and every request will be passed along accordingly. 这允许我动态地向API添加资源,并且相应地传递每个请求。 To illustrate: 为了显示:

// app.js

var express = require('express');
var mongoose = require('mongoose');

var app = express();
app.use(express.bodyParser());

mongoose.connect('mongodb://localhost/kittens');
var db = mongoose.connection;

var resources = [
  'kitten'
];

var repositories = {};

for (var i = 0; i < resources.length; i++) {
  var resource = resources[i];
  repositories[resource] = require('./api/' + resource);
}

db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function callback() {
  console.log('Successfully connected to MongoDB.');

  app.get('/:resource', function (req, res) {
    res.type('application/json');
    repositories[req.params.resource].findAll(res);
  });

  app.get('/:resource/:id', function (req, res) {
    res.type('application/json');
    repositories[req.params.resource].findOne(req, res);
  });

  app.listen(process.env.PORT || 4730);
});

- -

// api/kitten.js

var mongoose = require('mongoose');

var kittenSchema = mongoose.Schema({
  name: String
});

var Kitten = mongoose.model('Kitten', kittenSchema);

exports.findAll = function (res) {
  Kitten.find(function (err, kittens) {
    if (err) {
    }
    res.json(kittens);
  });
};

exports.findOne = function (req, res) {
  Kitten.findOne({ _id: req.params.id}, function (err, kitten) {
    if (err) {
    }
    res.json(kitten);
  });
};

Obviously, only a couple of methods have been implemented so far. 显然,到目前为止只实施了几种方法。 What do you guys think of this approach? 你们怎么看待这种方法? Anything I could improve on? 我还能改进什么吗?

Also, a small side question: I have to require mongoose in every API resource file (like in api\\kitten.js , is there a way to just globally require it in the app.js file or something? 另外,一个小问题:我必须在每个API资源文件中都需要api\\kitten.js (比如在api\\kitten.js ,有没有办法在app.js文件中全局要求它或什么?

Any input is greatly appreciated! 任何输入都非常感谢!

Well, you can separate out your routes, db models and templates in different files. 那么,您可以在不同的文件中分离您的路由,数据库模型和模板。 Have a directory structure something like this, 有一个像这样的目录结构,

| your_app
| -- routes
| -- models
| -- templates
| -- static
    | -- css
    | -- js
    | -- images
| -- config.js
| -- app.js
| -- url.js
  • For each Mongoose model have a separate file placed in your ./models 对于每个Mongoose模型,都有一个单独的文件放在./models
  • In templates directory place your jade files. 在模板目录中放置您的玉器文件。 (Assuming you are using jade as your template engine). (假设您使用jade作为模板引擎)。 Though it seems like you are only serving JSON, not HTML. 虽然看起来你只是提供JSON,而不是HTML。 Consider using Jade if you want to render HTML. 如果要呈现HTML,请考虑使用Jade。 (Here are few other template engines you can consider going with) (这里有一些你可以考虑使用的其他模板引擎
  • ./static directory for static JS, CSS and XML files etc. ./static目录,用于静态JS,CSS和XML文件等。
  • Things like db connections or 3rd party API keys and stuff can be put in config.js 像db连接或第三方API密钥和东西之类的东西可以放在config.js中
  • In url.js have a procedure which take express app object as argument and extend upon app.get and app.post there in single place. 在url.js中有一个过程,它将express app对象作为参数,并在app.getapp.post上扩展到单个位置。

PS This is the approach I go with for a basic web app in express. PS这是我在快递中使用基本Web应用程序的方法。 I am in no way saying this the best way to follow, but it helps me maintain my code. 我绝不是说这是最好的方法,但它有助于我维护我的代码。

There is no right way, but I did create a seed application for my personal directory structure to help my roommate with this. 没有正确的方法,但我确实为我的个人目录结构创建了种子应用程序,以帮助我的室友。

You can clone it: git clone https://github.com/hboylan/express-mongoose-api-seed.git 你可以克隆它: git clone https://github.com/hboylan/express-mongoose-api-seed.git

Or with npm: npm install express-mongoose-api-seed 或者使用npm: npm install express-mongoose-api-seed

As codemonger5 said there is no right way of organising directory structure. 正如codemonger5所说,没有正确的组织目录结构的方法。

However, you can use this boilerplate application for creating REST APIs using Express and mongoose using ES6. 但是,您可以使用样板应用程序使用Express和使用ES6的mongoose创建REST API。 We use the same directory structure in our production API services. 我们在生产API服务中使用相同的目录结构。

git clone https://github.com/KunalKapadia/express-mongoose-es6-rest-api
cd express-mongoose-es6-rest-api
npm install
npm start

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

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