[Hapi.js] Request Validation with Joi

hapi supports request validation out of the box using the joi module. Request path parameters, payloads, and querystring parameters can be validated with joi's simple, 

 

'use strict'
const Hapi = require('hapi')
const Joi = require('joi')
const server = new Hapi.Server()
server.connection({ port: 8000 })

server.route({
  method: ['POST','PUT'],
  path: '/user/{id?}',
  config: {
    validate: {
      params: Joi.object().keys({
        id: Joi.number()
      }),
      payload: Joi.object().keys({
        id: Joi.number()
        email: Joi.string()
      }).unknown(),
      query: Joi.object().keys({
        id: Joi.number()
      })
    },
    handler: function(request, reply) {
      reply({
        params: request.params,
        query: request.query
        payload: request.payload
      })
    }
  }
})

server.start(() => console.log(`Started at: ${server.info.uri}`))

 

你可能感兴趣的:([Hapi.js] Request Validation with Joi)