1.2.0 • Published 6 years ago
json-ok v1.2.0
json-ok  
  
 
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) stringIt 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 }