API 网关在阿里云函数体系中比较特殊,他类似于创建一个无触发器函数,通过平台网关的绑定,从而绑定到特定的路径上。
使用方式
在 f.yml 中配置函数,同时配置触发器类型。
service:name: midway-faas-examplesprovider:name: aliyunfunctions:apiGatewayTrigger:handler: index.handlerevents:- apigw: truepackage:artifact: code.zip
在 f deploy 后,参考阿里云文档配置即可。
:::info
当前 API 网关的 yml 配置写法过于复杂,暂时无法支持,请在平台进行配置。
:::
本地测试
midway faas 将 api 网关的代码结构和 http 保持了相同,业务不再需要返回特定的 JSON 结构,框架会自动转为 API 网关所需要的结构。
{"isBase64Encoded":true|false,"statusCode":httpStatusCode,"headers":{response headers},"body":"..."}
测试方式如下:
// testdescribe('/test/index.test.ts', () => {it('invoke', async () => {const result: any = await invoke({functionName: 'apiGatewayTrigger', // 函数名data: [ {path: '/api',method: 'POST', // 请求方法类型headers: {}, // 请求头query: {},pathParameters: {}, // 路径参数,比如 /api/:idbody: { // 请求的 bodyname: 'test'},}],});// API Gateway must be get a string textassert.deepEqual(result.body, '{"message":"Hello Midway FaaS!"}');});});// index.ts@Func('api.index')async handler() {console.log(this.ctx.method); // POSTconsole.log(this.ctx.path); // /apiconsole.log(this.ctx.request.body['name']); // testreturn {message: 'Hello Midway FaaS!',}}
HTTP Context API
Midway faas 在 http 和 API 网关场景下,将代码写法进行了简化,并向传统 koa 写法保持尽可能一致。
@Provide()export class APIService {@Inject()ctx: FaaSContext;@Func('index.get')async get() {const query = this.ctx.query;const url = this.ctx.path;const method = this.ctx.method;// 等价于 this.ctx.body = 'hello world'; 两者都支持return 'hello world';}@Func('index.post')async post() {const body = this.ctx.request.body;return this.ctx.method; // POST}}
:::info 直接 return 的内容,会被自动挂载到 ctx.body 中。 :::
详细文档,请访问函数上下文。
