1.2.1 • Published 5 years ago

koa-struct v1.2.1

Weekly downloads
2
License
MIT
Repository
github
Last release
5 years ago

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