• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

koajs/joi-router: Configurable, input and output validated routing for koa

原作者: [db:作者] 来自: 网络 收藏 邀请

开源软件名称:

koajs/joi-router

开源软件地址:

https://github.com/koajs/joi-router

开源编程语言:

JavaScript 100.0%

开源软件介绍:

joi-router

Easy, rich and fully validated koa routing.

NPM version build status Test coverage David deps npm download

Features:

Node compatibility

NodeJS >= 12 is required.

Example

const koa = require('koa');
const router = require('koa-joi-router');
const Joi = router.Joi;

const public = router();

public.get('/', async (ctx) => {
  ctx.body = 'hello joi-router!';
});

public.route({
  method: 'post',
  path: '/signup',
  validate: {
    body: {
      name: Joi.string().max(100),
      email: Joi.string().lowercase().email(),
      password: Joi.string().max(100),
      _csrf: Joi.string().token()
    },
    type: 'form',
    output: {
      200: {
        body: {
          userId: Joi.string(),
          name: Joi.string()
        }
      }
    }
  },
  handler: async (ctx) => {
    const user = await createUser(ctx.request.body);
    ctx.status = 201;
    ctx.body = user;
  }
});

const app = new koa();
app.use(public.middleware());
app.listen(3000);

Usage

koa-joi-router returns a constructor which you use to define your routes. The design is such that you construct multiple router instances, one for each section of your application which you then add as koa middleware.

const Koa = require("koa")
const router = require('koa-joi-router');

const pub = router();
const admin = router();
const auth = router();

// add some routes ..
pub.get('/some/path', async () => {});
admin.get('/admin', async () => {});
auth.post('/auth', async () => {});

const app = new Koa();
app.use(pub.middleware());
app.use(admin.middleware());
app.use(auth.middleware());
app.listen();

Module properties

.Joi

It is HIGHLY RECOMMENDED you use this bundled version of Joi to avoid bugs related to passing an object created with a different release of Joi into the router.

const koa = require('koa');
const router = require('koa-joi-router');
const Joi = router.Joi;

Router instance methods

.route()

Adds a new route to the router. route() accepts an object or array of objects describing route behavior.

const router = require('koa-joi-router');
const public = router();

public.route({
  method: 'post',
  path: '/signup',
  validate: {
    header: joiObject,
    query: joiObject,
    params: joiObject,
    body: joiObject,
    maxBody: '64kb',
    output: { '400-600': { body: joiObject } },
    type: 'form',
    failure: 400,
    continueOnError: false
  },
  pre: async (ctx, next) => {
    await checkAuth(ctx);
    return next();
  },
  handler: async (ctx) => {
    await createUser(ctx.request.body);
    ctx.status = 201;
  },
  meta: { 'this': { is: 'stored internally with the route definition' }}
});

or

const router = require('koa-joi-router');
const public = router();

const routes = [
  {
    method: 'post',
    path: '/users',
    handler: async (ctx) => {}
  },
  {
    method: 'get',
    path: '/users',
    handler: async (ctx) => {}
  }
];

public.route(routes);
.route() options
  • method: required HTTP method like "get", "post", "put", etc
  • path: required string
  • validate
    • header: object which conforms to Joi validation
    • query: object which conforms to Joi validation
    • params: object which conforms to Joi validation
    • body: object which conforms to Joi validation
    • maxBody: max incoming body size for forms or json input
    • failure: HTTP response code to use when input validation fails. default 400
    • type: if validating the request body, this is required. either form, json or multipart
    • formOptions: options for co-body form parsing when type: 'form'
    • jsonOptions: options for co-body json parsing when type: 'json'
    • multipartOptions: options for busboy parsing when type: 'multipart'
    • output: see output validation
    • continueOnError: if validation fails, this flags determines if koa-joi-router should continue processing the middleware stack or stop and respond with an error immediately. useful when you want your route to handle the error response. default false
    • validateOptions: options for Joi validate. default {}
  • handler: required async function or functions
  • pre: async function or function, will be called before parser and validators
  • meta: meta data about this route. koa-joi-router ignores this but stores it along with all other route data

.get(),post(),put(),delete() etc - HTTP methods

koa-joi-router supports the traditional router.get(), router.post() type APIs as well.

const router = require('koa-joi-router');
const admin = router();

// signature: router.method(path [, config], handler [, handler])

admin.put('/thing', handler);
admin.get('/thing', middleware, handler);
admin.post('/thing', config, handler);
admin.delete('/thing', config, middleware, handler);

.use()

Middleware run in the order they are defined by .use()(or .get(), etc.) They are invoked sequentially, requests start at the first middleware and work their way "down" the middleware stack which matches Express 4 API.

const router = require('koa-joi-router');
const users = router();

users.get('/:id', handler);
users.use('/:id', runThisAfterHandler);

.prefix()

Defines a route prefix for all defined routes. This is handy in "mounting" scenarios.

const router = require('koa-joi-router');
const users = router();

users.get('/:id', handler);
// GET /users/3 -> 404
// GET /3 -> 200

users.prefix('/users');
// GET /users/3 -> 200
// GET /3 -> 404

.param()

Defines middleware for named route parameters. Useful for auto-loading or validation.

See @koa/router

const router = require('koa-joi-router');
const users = router();

const findUser = (id) => {
  // stub
  return Promise.resolve('Cheddar');
};

users.param('user', async (id, ctx, next) => {
  const user = await findUser(id);
  if (!user) return ctx.status = 404;
  ctx.user = user;
  await next();
});

users.get('/users/:user', (ctx) => {
  ctx.body = `Hello ${ctx.user}`;
});

// GET /users/3 -> 'Hello Cheddar'

.middleware()

Generates routing middleware to be used with koa. If this middleware is never added to your koa application, your routes will not work.

const router = require('koa-joi-router');
const public = router();

public.get('/home', homepage);

const app = koa();
app.use(public.middleware()); // wired up
app.listen();

Additions to ctx.state

The route definition for the currently matched route is available via ctx.state.route. This object is not the exact same route definition object which was passed into koa-joi-router, nor is it used internally - any changes made to this object will not have an affect on your running application but is available to meet your introspection needs.

const router = require('koa-joi-router');
const public = router();
public.get('/hello', async (ctx) => {
  console.log(ctx.state.route);
});

Additions to ctx.request

When using the validate.type option, koa-joi-router adds a few new properties to ctx.request to faciliate input validation.

ctx.request.body

The ctx.request.body property will be set when either of the following validate.types are set:

  • json
  • form

json

When validate.type is set to json, the incoming data must be JSON. If it is not, validation will fail and the response status will be set to 400 or the value of validate.failure if specified. If successful, ctx.request.body will be set to the parsed request input.

admin.route({
  method: 'post',
  path: '/blog',
  validate: { type: 'json' },
  handler: async (ctx) => {
    console.log(ctx.request.body); // the incoming json as an object
  }
});

form

When validate.type is set to form, the incoming data must be form data (x-www-form-urlencoded). If it is not, validation will fail and the response status will be set to 400 or the value of validate.failure if specified. If successful, ctx.request.body will be set to the parsed request input.

admin.route({
  method: 'post',
  path: '/blog',
  validate: { type: 'form' },
  handler: async (ctx) => {
    console.log(ctx.request.body) // the incoming form as an object
  }
});

ctx.request.parts

The ctx.request.parts property will be set when either of the following validate.types are set:

  • multipart

multipart

When validate.type is set to multipart, the incoming data must be multipart data. If it is not, validation will fail and the response status will be set to 400 or the value of validate.failure if specified. If successful, ctx.request.parts will be set to an await-busboy object.

admin.route({
  method: 'post',
  path: '/blog',
  validate: { type: 'multipart' },
  handler: async (ctx) => {
    const parts = ctx.request.parts;
    let part;

    try {
      while ((part = await parts)) {
        // do something with the incoming part stream
        part.pipe(someOtherStream);
      }
    } catch (err) {
      // handle the error
    }

    console.log(parts.field.name); // form data
  }
});

Handling non-validated input

Note: if you do not specify a value for validate.type, the incoming payload will not be parsed or validated. It is up to you to parse the incoming data however you see fit.

admin.route({
  method: 'post',
  path: '/blog',
  validate: { },
  handler: async (ctx) => {
    console.log(ctx.request.body, ctx.request.
                      

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap