Skip to content

franciscop/json-ok

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

12 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

json-ok npm install json-ok test badge gzip size

A quick way of validating json objects using json-schema:

import ok from 'json-ok';

ok(24, { type: "number" });
// No issue

ok(24, { type: "string" });
// ValidationError: is not of a type(s) string

It is great to use to validate e.g. POST bodies:

// Express.js -> createUser.js
module.exports = app.post('/users/', function (req, res) {
  try {
    ok(req.body, bodySchema);
    // save user
    db.users.add(req.body, (error, user) => {
      if (error) return next(error);
      res.sendStatus(201);
    });
  } catch (error) {
    next(error);
  }
});

// Server.js -> createUser.js
module.exports = post('/users/', async ctx => {
  ok(ctx.body, bodySchema);
  await db.users.add(ctx.body);
  return 201;
});

This library is a thin wrapper around jsonschema with these improvements:

  • Throws errors instead of returning them.
  • Single, foolproof API ok(obj, schema).
  • It throws an actual Error instead of a random object.

You might also be interested on json-chaos to test your schema:

import chaos from 'json-chaos';

const person = { name: 'John', age: 21 };

console.log(chaos(person));
// { name: 45423, age: true }

About

A quick way of validating json objects using json-schema

Resources

Stars

Watchers

Forks

Packages

No packages published