1.0 版
单函数中间件
单函数中间件即只针对单个函数生效的 Web 中间件。
在 Midway Hooks 中,可以通过 withController 来支持单函数级别的中间件。全局中间件可参考:使用 Web 中间件
Demo 的 logger 与 classMiddleware 就是 Web 中间件。
使用函数中间件
import { withController } from '@midwayjs/hooks'import { FaaSContext } from '@midwayjs/faas'const logger = async (ctx: FaaSContext, next) => {const start = Date.now()await next()const cost = Date.now() - startconsole.log(`request ${ctx.url} cost ${cost}ms`)}export default withController({middleware: [logger]}, () => {return 'Hello Controller'})
使用 IoC 中间件
import { withController } from '@midwayjs/hooks'import { FaaSContext } from '@midwayjs/faas'import { Provide, ScopeEnum, Scope } from '@midwayjs/decorator'@Provide('classMiddleware')@Scope(ScopeEnum.Singleton)export class ClassMiddleware {resolve() {return async (ctx: FaaSContext, next) => {ctx.query.from = 'classMiddleware'await next()}}}export default withController({middleware: ['classMiddleware']}, () => {return 'Hello Controller ' + ctx.query.from})
API
withController
通过 withController 增强函数功能,第一个参数是 controller 配置,第二个参数是要执行的 FaaS 函数。
其中 controller 配置如下
- middleware(
any[]):可选参数,用于给当前的函数增加中间件功能,可以同时传入多个中间件。支持函数定义的中间件及 IoC 定义的中间件。
类型定义
type Controller = {middleware?: any[];};function withController(controller: Controller, func);
