npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

koa-sbv

v0.16.0

Published

Declarative schema validation for koa

Downloads

70

Readme

koa-sbv

Build Status npm version

Declarative body and query validation for koa that supports arbitrarily nested validation rules and tries to avoid verbosity of other packages.

Installation

npm install koa-sbv

Usage

  • every parameter that wasn't declared will be removed.
  • an error with 400 status code will be thrown if validation fails

More convenient way

One way is to use koa-sbv middleware that patches ctx object and makes ctx.validate available in next middleware functions.

const Koa = require('koa')
const parser = require('koa-body')
const sbv = require('koa-sbv')

const app = new Koa()

app.use(parser()).use(sbv.middleware)

/* ... */

router.post('/', async (ctx) => {
  ctx.validate(bodySchema)
})

More functional way

Alternative option is to use pure validation function and manually pass request body or query.

const { validate } = require('koa-sbv')

router.post('/', async (ctx) => {
  const body = validate(ctx.request.body, bodySchema, options)
  const query = validate(ctx.query, querySchema, options)
})

Examples

String validation

const sbv = require('koa-sbv')

const validated = validate(body, {
  a: 'string', // arbitrary string
  c: sbv.string({ min: 1, max: 10 }), // from 1 to 10 characters long
  d: /^\d{5}$/, // use RegExp for more advanced validation
})

Note: By default maximum allowed string length is 1e4, to allow longer strings explicitly pass max parameter.

Number validation

const sbv = require('koa-sbv')

const validated = validate(body, {
  a: 'number', // arbitrary number
  b: 'int', // integer
  c: 'uint', // non-negative integer
  d: sbv.number({ min: 0, max: 100 }), // any number from 0 to 100
  e: sbv.int({ max: 100 }), // any integer less than or equal 100
})

Arrays and objects

  • object literals are used to describe expected objects
  • array literals are used to describe expected arrays, first element describes elements of the array and second argument is used to provide additional options
    • min - minimum length of an array, default 0
    • max - maximum allowed length, default 1e3
    • len - if an array should contain exactly len elements
  • description can be nested as deep as necessary
  • dict helper can be used to validate objects with arbitrary number of key/value pairs
const { maybe, dict } = require('koa-sbv')

validate(body, {
  obj: { name: 'string', age: 'uint' },
  arr1: ['number'],
  arr2: ['number', { min: 1 }],
  arr3: [{ foo: 'string' }, { max: 10 }],
  map: dict('string', 'number'),
})

Optional parameters

By default all parameters are required, use maybe wrapper for optional parameters

const { maybe } = require('koa-sbv')

validate(body, {
  a: maybe('number'),
  b: maybe('number', 0), // second parameter is optional default value
  c: maybe(['string'], []),
})

Also null values are considered invalid by default, use nullable wrapper to allow them

const { nullable } = require('koa-sbv')

validate(body, {
  a: nullable('number'),
  b: nullable(['string']),
})

Additional validators

const sbv = require('koa-sbv')

validate(body, {
  data: 'json', // any array or object
  email: 'email',
  _id: 'ObjectId', // mongodb ObjectId
  id: 'uuid', // UUID version 1-5
  ans: sbv.oneOf('yes', 'no', true, false),
})

Custom validators

const sbv = require('koa-sbv')

sbv.define('isEven', (value, name) => {
  sbv.assert(value % 2 === 0, `${name} is not even`)
  return value
})

sbv.define('isOdd', (value, name) => {
  sbv.assert(value % 2 === 1, `${name} is not odd`)
  return value
})

validate(body, {
  a: 'isEven',
  b: ['isOdd', { len: 10 }],
})

Options object

By default all parameters are set to false

const options = {
  notStrict: true,
  parseNumbers: true,
  makeArrays: true,
}

validate(data, schema, options)
  • notStrict - make every parameter optional (otherwise it would be necessary to wrap everything in maybe)
  • parseNumbers - try to parse arguments as numbers if they where declared as number, int, or uint (e.g. '1' => 1, 'foo' => validation error)
  • makeArrays - make arrays from parameters if they were described as arrays (e.g. '1' => ['1'], ['1', '2'] => ['1', '2'])