0.1.0 • Published 6 years ago

validator-restify v0.1.0

Weekly downloads
2
License
ISC
Repository
github
Last release
6 years ago

restify-validator

npm install restify-validator --save

file: allValidation.js

'use strict';
var Joi = require('joi');


var validate = {
  login :{
    options: { flatten: true },
    body: {
    email: Joi.string().required().email(),
    password: Joi.string().required().min(6).max(10)
    }
  },
  register : {
  options: { flatten: true },
  body: {
    email: Joi.string().required().email(),
    password: Joi.string().required().min(6).max(10)
  }
}};
module.exports.validate =validate;

file: app.js

'use strict';

const restify = require("restify");
var validate = require('restify-validator');
var validation = require('./allValidator').validate;
global.httpErrors = restify.errors;

global.server = restify.createServer();
server.use(restify.plugins.bodyParser());
server.use(restify.plugins.acceptParser(server.acceptable));
server.use(restify.plugins.queryParser({
    mapParams: false
}));
server.use(restify.plugins.fullResponse());

server.on('restifyError', function(req, res, err, next) {
    // handle all errors passed to next here, whether it's Error or NotFoundError or anything that is an instance of Error
   res.status(err.status);
   res.json(err.errors); //res.send(err);
  });

server.listen(3000, function () {
    "use strict";
    console.log("server is up at 3000");
});

// generates a response function sending back to user the specified req[key]
function respondWith (key) {
  return function (req, res) {
    res.json(req[key]);
  };
}

function respond200 (req, res) {
  res.json(200);
}
server.post('/login', validate(validation.login), respond200);
server.post('/register', validate(validation.register), respond200);
// default errorhandler for express-validation
server.use(function (err, req, res, next) {
  res.status(400).json(err);
});


module.exports = server;

#Make sure to use this for error catching , tested in restify 5

server.on('restifyError', function(req, res, err, next) {
    // handle all errors passed to next here, whether it's Error or NotFoundError or anything that is an instance of Error
   res.status(err.status);
   res.json(err.errors); //res.send(err);
  });