nodeJS编写自己的中间件及示例返回字段由下划线改为驼峰的中间件

  Koa 是一个由 Express 原班人马打造的新的 web 框架,Koa 本身并没有捆绑任何中间件,只提供了应用(Application)、上下文(Context)、请求(Request)、响应(Response)四个模块。原本 Express 中的路由(Router)模块已经被移除,改为通过中间件的方式实现。相比较 Express,Koa 能让使用者更大程度上构建个性化的应用。

一、中间件简介

  Koa 是一个中间件框架,本身没有捆绑任何中间件。本身支持的功能并不多,功能都可以通过中间件拓展实现。通过添加不同的中间件,实现不同的需求,从而构建一个 Koa 应用。

  Koa 的中间件就是函数,可以是 async 函数,或是普通函数,以下是官网的示例:

// async 函数
app.use(async (ctx, next) => {
  const start = Date.now();
  await next();
  const ms = Date.now() - start;
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`);
});

// 普通函数
app.use((ctx, next) => {
  const start = Date.now();
  return next().then(() => {
    const ms = Date.now() - start;
    console.log(`${ctx.method} ${ctx.url} - ${ms}ms`);
  });
});

  中间件可以通过官方维护的仓库查找获取,也可以根据需求编写属于自己的中间件。

二、中间件原理

  下面是一个的 Koa 应用,简单演示了中间件的执行顺序:

const Koa = require('Koa');
const app = new Koa();

// 最外层的中间件
app.use(async (ctx, next) => {
    await console.log(`第 1 个执行`);
    await next();
    await console.log(`第 8 个执行`);
});

// 第二层中间件
app.use(async (ctx, next) => {
    await console.log(`第 2 个执行`);
    await console.log(`第 3 个执行`);
    await next();
    await console.log(`第 6 个执行`);
    await console.log(`第 7 个执行`);
});

// 最里层的中间件
app.use(async (ctx, next) => {
    await console.log(`第 4 个执行`);
    ctx.body = "Hello world.";
    await console.log(`第 5 个执行`);
});

app.listen(3000, () => {
    console.log(`Server port is 3000.`);
})

  原理:从上面的示例中可以看出,中间件的执行顺序并不是从头到尾,而是类似于前端的事件流。事件流是先进行事件捕获,到达目标,然后进行事件冒泡。中间件的实现过程也是一样的,先从最外面的中间件开始执行,next() 后进入下一个中间件,一路执行到最里面的中间件,然后再从最里面的中间件开始往外执行

  Koa 中间件采用的是洋葱圈模型,每次执行下一个中间件传入两个参数 ctx 和 next,参数 ctx 是由 koa 传入的封装了 request 和 response 的变量,可以通过它访问 request 和 response,next 就是进入下一个要执行的中间件。

三、编写属于自己的中间件

  中间件有两个重点:

  (1)调用 app.use() 来应用一个中间件;

  (2)调用 next() 继续执行下一个中间件(可能不存在更多的中间件,只是让执行继续下去)。

1、token 验证的 middleware

  前后端分离开发,我们常采用 JWT 来进行身份验证,其中 token 一般放在 HTTP 请求中的 Header Authorization 字段中,每次请求后端都要进行校验,如 Java 的 Spring 框架可以在过滤器中对 token 进行统一验证,而 Koa 则通过编写中间件来实现 token 验证。

// token.js
// token 中间件
module.exports = (options) => async (ctx, next) {
  try {
    // 获取 token
    const token = ctx.header.authorization
    if (token) {
      try {
          // verify 函数验证 token,并获取用户相关信息
          await verify(token)
      } catch (err) {
        console.log(err)
      }
    }
    // 进入下一个中间件
    await next()
  } catch (err) {
    console.log(err)
  }
}
// app.js
// 引入 token 中间件
const Koa = require('Koa');
const app = new Koa();
const token = require('./token')

app.use(token())

app.listen(3000, () => {
    console.log(`Server port is 3000.`);
})

2、log 的 middleware

  日志模块也是线上不可缺少的一部分,完善的日志系统可以帮助我们迅速地排查出线上的问题。通过 Koa 中间件,我们可以实现属于自己的日志模块

// logger.js
// logger 中间件
const fs = require('fs')
module.exports = (options) => async (ctx, next) => {
  const startTime = Date.now()
  const requestTime = new Date()
  await next()
  const ms = Date.now() - startTime;
  let logout = `${ctx.request.ip} -- ${requestTime} -- ${ctx.method} -- ${ctx.url} -- ${ms}ms`;
  // 输出日志文件
  fs.appendFileSync('./log.txt', logout + '\n')
}
// app.js
// 引入 logger 中间件
...const logger = require('./logger')
app.use(logger())
...
app.listen(3000, () => {
    console.log(`Server port is 3000.`);
})

  可以结合 log4js 等包来记录更详细的日志。

3、返回字段由下划线改为驼峰的中间件

// toHump.js
const toHump = async (ctx, next) => {
    ctx.write = (obj) => ctx.body = toHumpFun(obj)
    await next()
}

function toHumpFun(obj) {
    const result = Array.isArray(obj) ? [] : {}
    for (const key in obj) {
        if (obj.hasOwnProperty(key)) {
            const element = obj[key];
            const index = key.indexOf('_')
            let newKey = key
            if (index === -1 || key.length === 1) {
                result[key] = element
            } else {
                const keyArr = key.split('_')
                const newKeyArr = keyArr.map((item, index) => {
                    if (index === 0) return item
                    return item.charAt(0).toLocaleUpperCase() + item.slice(1)
                })
                newKey = newKeyArr.join('')
                result[newKey] = element
            }

            if (typeof element === 'object' && element !== null) {
                result[newKey] = toHumpFun(element)
            }
        }
    }
    return result
}

module.exports = toHump
// app.js
const toHump = require('./toHump')
app.use(toHump) // 需要放在引用路由之前

  使用 ctx.write(data) 替换 ctx.body = data

  我们已经了解中间件的原理,以及如何实现一个自己的中间件中间件的代码通常比较简单,我们可以通过阅读官方维护的仓库中优秀中间件的源码,来加深对中间件的理解和运用。

posted @ 2020-08-11 15:53  古兰精  阅读(1475)  评论(0编辑  收藏  举报