koa-middle
TypeScript icon, indicating that this package has built-in type declarations

1.0.1 • Public • Published

koa-middle

简单的koa中间件创建工具

使用

// example
const {createRule, createMiddleware} = require('koa-middle')
const Koa = new require('koa')
const app = new Koa()

app.use(createMiddleware([
  createRule('method').accordance('POST'),
  createRule('url').startsWith('/jsonrpc')
], async function (ctx, next) {
  // 你的中间件逻辑
}))

app.listen(8080)

API

createRule

创建 Koa.Context 的检验规则函数。该函数拥有以下方法:

  • accordance(data: any) 是否与给出的值相等
  • difference(data: any) 是否与给出的值不一致
  • existence() 是否存在值
  • startsWith(str: string) - 是否以给出的字符串开头
  • endsWith(str: string) - 是否以给出的字符串结尾
  • includes(data: array | string) - 是不是给出的数组(或字符串)的一部分
  • test(reg: RegExp) - 是否通过正在测试
  • custom(fn: Function) - 自定义复杂的校验规则

上述方法皆返回校验函数本身,所以可以链式调用

// example
const rule = createRule('name')
  .accordance('some value')
  .difference('diff value')
  .existence()
  .startsWith('string')
  .endsWith('string')
  .includes('values or string')
  .test(/regexp/)
  .custom(function customValidator (value) {
    return true // or false
  });

createMiddleware

创建中间件。

// example
const hasToken = headers => !!headers['x-access-token']
const middleware = createMiddleware([
  createRule('method').accordance('GET'),
  createRule('url').startsWith('/api'),
  createRule('headers').cutsom(hasToken)
], function middlewareHandler (ctx, next) {
  // 逻辑代码 ...
})

app.use(middleware)

curryMiddleware

规则复用。

// example
const hasToken = headers => !!headers['x-access-token']
const rules = [
  createRule('method').accordance('GET'),
  createRule('url').startsWith('/api'),
  createRule('headers').cutsom(hasToken)
]
const middlewareCreator = curryMiddleware(rules)

app.use(middlewareCreator(function handler1(ctx, next) {}))
app.use(middlewareCreator(function handler2(ctx, next) {}))
app.use(middlewareCreator(function handler3(ctx, next) {}))
// more ...

Package Sidebar

Install

npm i koa-middle

Weekly Downloads

0

Version

1.0.1

License

MIT

Unpacked Size

6.11 kB

Total Files

4

Last publish

Collaborators

  • applet.im