koa-struct

1.2.1 • Public • Published

koa-struct

Koa struct middleware

Installation

koa-struct requires

  • koa2
  • koa-body
  • koa-router
npm install koa-struct --save

Example

Basic usage

const struct = require('koa-struct');
const body = require('koa-body');
const Router = require('koa-router');
const koa = require('koa');
 
const app = new koa();
const router = new Router();
 
app
    .use(body())
    .use(struct())
    .use(router.routes())
    .use(router.allowedMethods());
 
router.post('/user/update', ctx => {
 
    ctx.struct({
        username: 'string',
        email: 'email',
        age: 'number'
    });
 
    ctx.body = 'ok';
});
 
app.listen(3000);

Validate params

router.post('/user/update/:id', ctx => {
 
    ctx.structParam({
        id: 'number'
    });
 
    ctx.body = 'ok';
});

Validate query

router.get('/user/?id=255', ctx => {
 
    ctx.structQuery({
        id: 'number'
    });
 
    ctx.body = 'ok';
});

Validation

koa-struct uses Valify to validating data, so consider it for documentation and options.

Valify options

// Globals
app.use(struct({
    autoCast: false
));
 
// Locals
router.post('/user/update', ctx => {
    ctx.struct({
        username: 'string',
        email: 'email',
        age: 'number'
    }, {
        autoCast: false
    });
    ctx.body = 'ok';
});

By default autoCast is set to true.

For more info about Valify click here

Changelog

You can view the changelog here

License

koa-struct is open-sourced software licensed under the MIT license

Authors

Fabio Ricali

Package Sidebar

Install

npm i koa-struct

Weekly Downloads

2

Version

1.2.1

License

MIT

Unpacked Size

9.91 kB

Total Files

6

Last publish

Collaborators

  • fabioricali