Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

body-expect

Package Overview
Dependencies
Maintainers
1
Versions
8
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

body-expect

Simple package for validate request body in Koa, Express... or anywhere.

  • 0.4.2
  • latest
  • Source
  • npm
  • Socket score

Version published
Maintainers
1
Created
Source

body-expect

Simple package for validate request body in Koa, Express... or anywhere.

Install

$ npm i body-expect

Usage

Express

const express = require('express');
const bodyParser = require('body-parser');
const expect = require('body-expect/express');

const app = express();

app.use(bodyParser.json());

app.use((req, res, next) => {
  req.params = {
    ...req.params,
    ...req.query,
    ...req.body,
  };

  next();
});

app.post(
  '/users',
  expect({
    age: {
      type: Number,
      validate: age => age >= 18,
    },
    name: String,
    hobby: {
      type: String,
      required: false,
    },
  }),
  (req, res) => {
    if (req.validationErrors && req.validationErrors.length) {
      res.status(400).json({
        error: `Bad request data: ${req.validationErrors.join(', ')}`, 
      });
      
      return;
    }
    
    // business logic here ...
  },
);

app.listen(process.env.PORT);

Koa

const Koa = require('koa');
const Router = require('koa-router');
const bodyParser = require('koa-bodyparser');
const expect = require('body-expect/koa');

const app = new Koa();
const router = new Router();

router.post(
  '/goals',
  expect({
    text: String,
    date: Number,
  }),
  (ctx) => {
    // business logic here ...
  },
);

app.use(bodyParser());

app.use(async (ctx, next) => {
  ctx.params = {
    ...ctx.params,
    ...ctx.query,
    ...ctx.request.body,
  };

  await next();
});

app.use(async (ctx, next) => {
  try {
    await next();
  } catch (err) {    
    ctx.status = err.status || 500;
    ctx.body = err.message || 'Server error.';
  }
});

app.use(router.routes());

app.listen(process.env.PORT);

Abstract

const createSchema = require('body-expect');

const expect = createSchema({
  foo: String,
});

const errors = expect({});

FAQs

Package last updated on 01 Mar 2019

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc