1.0.0 • Published 4 years ago
koa-joi v1.0.0
koa-joi
Koa middleware for validating requests using @hapi/joi
Version 2.x is a complete re-write of this library to support Koa2
and @hapi/joi
.
Version 1.x can be found on the v1 branch and was originally created by Pierre Inglebert
Installation
npm install koa-joi
Example
import Koa from 'koa'
import Joi from '@hapi/joi'
import bodyParser from 'koa-bodyparser'
import { validateBody } from 'koa-joi'
/**
* Init application
*
* @constant {Koa} app
*/
const app = new Koa()
app.use(bodyParser())
/**
* Request body schema
*
* @constant {Joi.Schema} bodySchema
*/
const bodySchema = Joi.object({
name: Joi.string().required()
})
app.use(validateBody(bodySchema))
/**
* Function logic
*
* @param {Koa.Context} ctx
*/
ctx.use(async (ctx) => {
const { name } = ctx.request.body
ctx.body = `Hello, ${name}`
ctx.status = 200
})
// start server
app.listen(3000)
console.info('listening at http://127.0.0.1:3000')