Midway FaaS 在 HTTP/API 网关触发器,对请求出入参做了处理,尽可能规则化为 koa2 形式,所以,在一定程度上,可以兼容 koa2 的中间件。
Web 中间件分两类,全局中间件和单函数中间件,使用上有一些区别,但是都是通过 IoC 体系进行注入使用。
定义 Web 中间件
你可以在项目的子目录(比如 middleware 或者 mw)中创建中间件文件,比如 static.ts ,用于支持 koa-static 。
// middleware/static.tsimport { Provide, ScopeEnum, Scope, Config } from '@midwayjs/decorator';import * as serve from 'koa-static';@Provide('staticMiddleware')@Scope(ScopeEnum.Singleton)export class StaticMiddleware {@Config('static')staticConfig; // 在 config 中的配置resolve() {return serve(__dirname + '/test/fixtures', this.staticConfig);}}
也可以自由执行逻辑。
import { Provide, ScopeEnum, Scope } from '@midwayjs/decorator';import * as serve from 'koa-static';@Provide('customMiddleware')@Scope(ScopeEnum.Singleton)export class StaticMiddleware {resolve() {return async (ctx, next) => {// xxxxxawait next();// xxxxx}}}
使用
全局中间件
在 config.default.ts 的 middleware 配置中填入上面定义的中间件 Provide 出的 id。
// config.default.tsexport const middleware = [ 'staticMiddleware' ];
函数级别 Web 中间件
在 @Func 装饰器的 middleware 属性写入 id。
import { FunctionHandler, FaaSContext } from '@midwayjs/faas';import { Provide, Inject, Func } from '@midwayjs/decorator';@Provide()export class IndexHandler implements FunctionHandler {@Inject()ctx: FaaSContext;@Func('index.handler', { middleware: ['staticMiddleware'] })async handler() {return 'hello world';}}
已封装的中间件
Cookie
用于提供 Cookie 解析的能力。
安装方式
**
无 ,已默认开启。
使用
**
配置
// 是否 cookies 加密export const cookies = {secure: false,};// cookie 加密 keyexport const keys = '';
import {FunctionHandler,} from '@midwayjs/faas';import { Provide, Inject, Func } from '@midwayjs/decorator';@Provide()export class IndexHandler implements FunctionHandler {@Inject()ctx;@Func('index.handler')async handler() {// set cookiethis.ctx.cookies.set('bbbb', 123);// get cookiethis.ctx.cookies.get('bbb');}}
StaticFile
用于提供静态资源托管能力。
安装方式
npm i @midwayjs/faas-middleware-static-file --save
使用
**
配置,和 koa-session 相同。
// configexports.staticFile = {prefix: '/public/',dir: join(appInfo.baseDir, '../public')};
**
import { FunctionHandler, FaaSContext } from '@midwayjs/faas';import { Provide, Inject, Func } from '@midwayjs/decorator';@Provide()export class IndexHandler implements FunctionHandler {@Inject()ctx: FaaSContext;@Func('index.handler', { middleware: ['fmw:staticFile'] })async handler() {}}
Upload
用于函数网关的文件上传能力
安装方式
npm i @midwayjs/faas-middleware-upload --save
使用
**
配置:
// config/config.default.tsexport const upload = {mod: 'stream', // 支持三种模式,默认为stream,还支持buffer 和 file,对应的 file.data 分别为 ReadStream、File Data Buffer 和 临时文件地址}
添加组件:
// configuration.tsimport { Configuration } from '@midwayjs/decorator';@Configuration({importConfigs: ['./config/'],imports: ['@midwayjs/faas-middleware-upload']})export class ContainerConfiguration { }
使用:
// index.tsimport { FunctionHandler, FaaSContext } from '@midwayjs/faas';import { Provide, Inject, Func } from '@midwayjs/decorator';@Provide()export class IndexHandler implements FunctionHandler {@Inject()ctx: FaaSContext;@Func('index.handler', { middleware: ['fmw:upload'] })async handler() {const files = (this.ctx as any).files;/*files = [{filename: "20210118142906.jpg",data: FileReadStream, // 还支持其他模式,参照配置中的 mod 参数fieldname: "fileFormName",mimeType: "image/jpeg"}]*/const fields = (this.ctx as any).fields;/*fields = {formKey: formValue}*/}}
