How to use express-validation - 10 common examples

To help you get started, we’ve selected a few express-validation examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github frontendbr / eventos-api / test / middleware / init.error.handler.middleware.spec.js View on Github external
const expressValidation = require('express-validation')
      const app = {
        use: function (next) {
          middleware = next
        }
      }

      error({
        app
      })

      const errors = {}
      const options = {
        status: 400
      }
      const errorThrow = new expressValidation.ValidationError(errors, options)
      const req = {}
      const res = {
        status: () => {}
      }

      const status = sinon.stub(res, 'status').returns({
        json: () => {}
      })

      // simulando a chamada do middleware
      middleware(errorThrow, req, res, next)
      status.should.have.been.calledWith(400)
    })
github andy6804tw / RESTful_API_start_kit / src / server / routes / article.route.js View on Github external
import express from 'express';
import validate from 'express-validation';
import articleCtrl from '../controllers/article.controller';
import paramValidation from '../../config/param-validation';

const router = express.Router();

router.route('/')
  .get(articleCtrl.articleGet) /** 取得 Article 所有值組 */
  .post(validate(paramValidation.createArticle), articleCtrl.articlePost); /** 新增 Article 值組 */

router.route('/:article_id')
  .put(articleCtrl.articlePut) /** 修改 Article 值組 */
  .delete(articleCtrl.articleDelete); /** 刪除 Article 值組 */

/** 利用 Middleware 取得 Header 中的 Rearer Token */
const ensureToken = (req, res, next) => {
  const bearerHeader = req.headers.authorization;
  if (typeof bearerHeader !== 'undefined') {
    const bearer = bearerHeader.split(' '); // 字串切割
    const bearerToken = bearer[1]; // 取得 JWT
    req.token = bearerToken; // 在response中建立一個token參數
    next(); // 結束 Middleware 進入 articleCtrl.articlePersonalGet
  } else {
    res.status(403).send(Object.assign({ code: 403 }, { message: '您尚未登入!' })); // Header 查無 Rearer Token
  }
github andy6804tw / RESTful_API_start_kit / src / config / express.js View on Github external
app.use((err, req, res, next) => {console.log('1')
  let errorMessage;
  let errorCode;
  let errorStatus;
  // express validation error 所有傳入參數驗證錯誤
  if (err instanceof expressValidation.ValidationError) {
    if (err.errors[0].location === 'query' || err.errors[0].location === 'body') {
      errorMessage = err.errors[0].messages;
      errorCode = 400;
      errorStatus = httpStatus.BAD_REQUEST;
    }
    const error = new APPError.APIError(errorMessage, errorStatus, true, errorCode);
    return next(error);
  }
  return next(err);
});
github garage-it / SmartHouse-backend / src / API / users / user.routes.js View on Github external
import express from 'express';
import validate from 'express-validation';
import paramValidation from '../../config/param-validation';
import userCtrl from './user.controller.js';

const router = express.Router();    // eslint-disable-line new-cap

router.route('/')
    /** GET /api/users - Get list of users */
    .get(userCtrl.list)

    /** POST /api/users - Create new user */
    .post(validate(paramValidation.createUser), userCtrl.create);

router.route('/:userId')
    /** GET /api/users/:userId - Get user */
    .get(userCtrl.get)

    /** PUT /api/users/:userId - Update user */
    .put(validate(paramValidation.updateUser), userCtrl.update)

    /** DELETE /api/users/:userId - Delete user */
    .delete(userCtrl.remove);

/** Load user when API with userId route parameter is hit */
router.param('userId', userCtrl.load);

export default router;
github linnovate / mean / server / routes / auth.route.js View on Github external
import express from 'express';
import validate from 'express-validation';
import expressJwt from 'express-jwt';
import paramValidation from '../config/param-validation';
import authCtrl from '../controllers/auth.controller';
import config from '../config/config';

const router = express.Router(); // eslint-disable-line new-cap

/** POST /api/auth/login - Returns token if correct username and password is provided */
router.route('/login')
  .post(validate(paramValidation.login), authCtrl.login);

/** GET /api/auth/random-number - Protected route,
 * needs token returned by the above as header. Authorization: Bearer {token} */
router.route('/random-number')
  .get(expressJwt({ secret: config.jwtSecret }), authCtrl.getRandomNumber);

export default router;
github thanhle09t2bkdn / blog-server-es7 / server / routes / api / v1 / CategoryRouter.js View on Github external
import {categoryController} from '../../../controllers/api/v1';
import { Router } from 'express';
import {categoryValidation} from '../../../validations';
import {auth} from '../../../middlewares';
import Validate from 'express-validation';

const router = Router(); // eslint-disable-line new-cap

router.route('/index').get([Validate(categoryValidation.index), auth.mustLogin], categoryController.index);
router.route('/view').get([Validate(categoryValidation.view), auth.mustLogin], categoryController.view);

export default router;
github SoftwareEngineeringDaily / software-engineering-daily-api / server / routes / comment.route.js View on Github external
import config from '../../config/config';

const router = express.Router(); // eslint-disable-line new-cap


router.route('/forEntity/:entityId')
  .get(
    expressJwt({
      secret: config.jwtSecret,
      credentialsRequired: false
    }),
    commentCtrl.list
  )
  .post(
    expressJwt({ secret: config.jwtSecret })
    , validate(paramValidation.comment)
    , commentCtrl.create
  );

router.route('/:commentId/upvote')
  .post(
    expressJwt({ secret: config.jwtSecret })
    // TODO: refactor to have these into one call like upvote: [method1, method2,...]
    // upvoteHandlers
    , transferField({ source: 'comment', target: 'entity' })
    , voteCtrl.findVote
    , voteCtrl.upvote // rename to upvoteHelper
    , voteCtrl.finish // IF we add a model.unlike we don't really need this..
  );

router.route('/:commentId')
  .put(
github garage-it / SmartHouse-backend / src / API / users / user.routes.js View on Github external
const router = express.Router();    // eslint-disable-line new-cap

router.route('/')
    /** GET /api/users - Get list of users */
    .get(userCtrl.list)

    /** POST /api/users - Create new user */
    .post(validate(paramValidation.createUser), userCtrl.create);

router.route('/:userId')
    /** GET /api/users/:userId - Get user */
    .get(userCtrl.get)

    /** PUT /api/users/:userId - Update user */
    .put(validate(paramValidation.updateUser), userCtrl.update)

    /** DELETE /api/users/:userId - Delete user */
    .delete(userCtrl.remove);

/** Load user when API with userId route parameter is hit */
router.param('userId', userCtrl.load);

export default router;
github amida-tech / api-boilerplate / server / routes / user.route.js View on Github external
import express from 'express';
import validate from 'express-validation';
import paramValidation from '../../config/param-validation';
import userCtrl from '../controllers/user.controller';

const router = express.Router(); // eslint-disable-line new-cap

router.route('/')

    /** GET /api/users - Get list of users */
    .get(userCtrl.list)

    /** POST /api/users - Create new user */
    .post(validate(paramValidation.createUser), userCtrl.create);

router.route('/:userId')

    /** GET /api/users/:userId - Get user */
    .get(userCtrl.get)

    /** PUT /api/users/:userId - Update user */
    .put(validate(paramValidation.updateUser), userCtrl.update)

    /** DELETE /api/users/:userId - Delete user */
    .delete(userCtrl.remove);

/** Load user when API with userId route parameter is hit */
router.param('userId', userCtrl.load);

export default router;
github kunalkapadia / express-mongoose-es6-rest-api / config / express.js View on Github external
app.use((err, req, res, next) => {
  if (err instanceof expressValidation.ValidationError) {
    // validation error contains errors which is an array of error each containing message[]
    const unifiedErrorMessage = err.errors.map(error => error.messages.join('. ')).join(' and ');
    const error = new APIError(unifiedErrorMessage, err.status, true);
    return next(error);
  } else if (!(err instanceof APIError)) {
    const apiError = new APIError(err.message, err.status, err.isPublic);
    return next(apiError);
  }
  return next(err);
});

express-validation

express-validation is a middleware that validates a request and returns a response with errors; if any of the configured validation rules fail.

MIT
Latest version published 5 months ago

Package Health Score

76 / 100
Full package analysis