How to separate the routes and models from app.js using NodeJS and Express

后端 未结 3 635
生来不讨喜
生来不讨喜 2021-01-30 04:13

I\'m creating an app using Node and Express. However, I can see it\'ll soon become difficult to manage all the routes that are placed inside app.js. I have placed

3条回答
  •  北海茫月
    2021-01-30 05:11

    I can suggest you this file structure (according to Modular web applications with Node.js and Express from tjholowaychuk):

    app.js
       modules
          users
             index.js
             model.js
          users-api
             index.js
          static-pages
             index.js
    

    user-api and static-pages export expressjs applications, you can easily mount them in app.js. In users module you can describe some Data Access operations and all methods about manipulating with the User entity (like create, update etc.). Our API module will use all these methods.

    And here is sample code of app.js file (without common express stuff, only mounting routes from different modules):

    var express = require('express');
    var app = express();
    
    // mount all the applications
    app.use('/api/v1', require("user-api"));
    app.use(require("static-pages"));
    
    app.listen(3000);
    

    To use your modules this way you must start your app like this NODE_PATH=modules node app.js (i put this line to package.json file in scripts section).

    Here is sample code of users module:

    index.js

    User = require("./model");
    
    module.exports = {
        get: function(id, callback) {
            User.findOne(id, function(err, user) {
               callback(err, user);
            });
        },
        create: function(data, callback) {
            // do whatever with incoming data here
            data = modifyDataInSomeWay(data);
            var newUser = new User(data);
            newUser.save(function(err, savedUser) {
                // some logic here
                callback(err, savedUser); 
            });
        }
    };
    

    model.js (with Mongoose stuff for example of course!)

    var mongoose = require('mongoose');
    var Schema = mongoose.Schema;
    
    var User = new Schema({
        firstname   : {type: String, required: false},
        lastname    : {type: String, required: false},
        email       : {type: String, required: true}
    });
    
    module.exports = mongoose.model('user', User);
    

    And example of user-api module (here is the main part of the answer about separating routes and models).

    var users = require("users");
    
    var express = require("express");
    var app = module.exports = express(); // we export new express app here!
    
    app.post('/users', function(req, res, next) {
        // try to use high-level calls here
        // if you want something complex just create another special module for this
        users.create(req.body, function(err, user) {
            if(err) return next(err); // do something on error
            res.json(user); // return user json if ok
        });
    });
    

    And example of static-pages. If you are not going to build a kind of REST interface you may simply create several modules that will render pages only.

    var express = require("express");
    var app = module.exports = express(); // we export new express app here again!
    
    app.get('/', function(req, res, next) {
        res.render('index', {user: req.user});
    });
    
    app.get('/about', function(req, res, next) {
        // get data somewhere and put it in the template
        res.render('about', {data: data});
    });
    

    Of course you can do whatever you want with modules. The main idea about expressjs is to use a lot of small apps instead of single one.

    About nodejs modules you can read stackoverflow and docs.

    Hope this helps.

提交回复
热议问题