Skip to content

shipharbor/json-schema-middleware

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

8 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

json-schema-middleware

stability npm version build status downloads js-standard-style

Middleware to validate your json schemas.

usage

One of the most common things for your code to consume in a node framework is probably going to be JSON. The problem is that it doesn't always come back in the nice format you might need. We gotchu tho: json-schema-middleware takes in a JSON schema and validates the request body against it. Here is how you would use it with merry:

var jsonSchemaMiddleware = require('json-schema-middleware')
var merry = require('merry')

var mw = merry.middleware
var mySchema = `
  {
    "required": true,
    "type": "object",
    "properties": {
      "hello": {
        "required": true,
        "type": "string"
      }
    }
  }
`

var app = merry()
app.router([
  ['/foo', mw([jsonSchemaMiddleware(mySchema), myCoolEndpoint])]
])

function myCoolEndpoint (req, res, ctx, done) {
  console.log('hot code bod', ctx.body)
  done(null, 'success!')
}

API

middleware.schema(string)

Takes a JSON string to validate the response against. It will parse and validate the res against the schema, and attach it to ctx.body as part of middleware. If an error occurs, json-schema-middleware will return a boom type error.

related content

LICENSE

MIT