oj5_rw
Last Updated: February 25, 2016
·
618
· dsdenes
0 upscw4bodubwawudgjohwsiwd2xou7wdarmewslq9frvpiywhverfvlvfkkzfeels0zdqjbxogwk

Express router chaining, REST API user adding, nodejs

router.js

const router = require('express').Router();
const User = require('./lib/user');

router.post('/api/users', 
  User.validateUser, 
  User.addUser, 
  User.sendValidationEmail,
  User.authenticateUser,
  function(req, res, next) {
    res.status(204).end();
  }
);  

lib/user.js

const co = require('co');
const q = require('q');
const passport = require('passport');

/* your own implementations come here */
const userMongooseModel = require('./db/userMongooseModel');
const email = require('./lib/email');

const validateUser = function(req, res, next) {
  co(function*() {

    if (!req.body.email) {
      return next(new Error('E-mail required'));
    }

    delete req.body.forbiddenkey;

    next();

  }).catch(function(error) {
    next(error);
  });
}

const addUser = function(req, res, next) {
  co(function*() {

    let user = yield userMongooseModel.create(req.body);

    // if your mongoose schema creates it, for the validation
    req.body.token = user.token;

    next();

  }).catch(function(error) {
    next(error);
  });
}

const sendValidationEmail = function(req, res, next) {
  co(function*() {

    yield email.sendActivationEmail(req.body.email, req.body.name, req.body.token);

    next();

  }).catch(function(error) {
    next(error);
  });
}

const authenticateUser = function(req, res, next) {

  passport.authenticate('local')(req, res, function () {
    req.session.save(function (error) {
      if (error) {
        return next(err);
      }
      next();
    });
  }); 

}

module.exports = {
 validateUser: validateUser,
 addUser: addUser,
 sendValidationEmail: sendValidationEmail,
 authenticateUser: authenticateUser
}
Say Thanks
Respond