Function Context
Event conversion
Midway Serverless has carried out input parameter wrapping according to the situation of different platforms. At the same time, when the function uses apigw(API gateway) and http (Aliyun) triggers, it has made special treatment on the input parameter (event). In order to simplify and unify the writing method, the event is unified and regularized into code similar to koa writing method.
Normal trigger scenario:
import { Context } from '@midwayjs/faas';
import { Provide } from '@midwayjs/core';
@Provide()
export class Index {
@Inject()
ctx: Context;
@ServerlessTrigger(...)
async handler(event) {
return 'hello world';
}
}
HTTP and API gateway trigger scenarios:
import { Context } from '@midwayjs/faas';
import { Provide } from '@midwayjs/core';
@Provide()
export class Index {
@Inject()
ctx: Context;
@ServerlessTrigger(...)
async handler() {
// The following two writing methods are the same
// this.ctx.body = 'hello world';
return 'hello world';
}
}
Context
Every time a function is called, a new ctx (function context) is created. For attributes or methods on ctx, we provide ts definitions.
In Serverless v1 era, our definition is called FaaSContext. In v2, we have unified the definition and application, which is more consistent.
ctx.logger
- return
ILogger
The log object of each request passed by the runtime. The default value is console.
ctx.logger.info('hello');
ctx.logger.warn('hello');
ctx.logger.error('hello');
ctx.env
- return
string
The current startup environment, that is, the value of the NODE_ENV or MIDWAY_SERVER_ENV. The default value is prod.
ctx.env; //default prod
ctx.requestContext
- return
MidwayRequestContainer
The IoC request scope container of midway faas is used to obtain object instances in other IoC containers.
const userService = await ctx.requestContext.getAsync(UserService);
FaaSHTTPContext
Context definitions are inherited from FaaSHTTPContext. The former retains the latter. In most scenarios, the former can be used directly. The latter is only available under apigw(API Gateway) and http (Aliyun) triggers.
For ordinary users, just use Context definition directly.
import { Context } from '@midwayjs/faas';
@Inject()
ctx: Context;
In the ctx object, we provide some API similar to writing traditional Koa Web applications. The advantage of this is to reduce the cognitive cost of users, and, to a certain extent, compatibility with the original traditional code and community middleware becomes possible.
We have provided some APIs similar to traditional APIs that support common capabilities. Different platforms may not be exactly the same. We will point out specific APIs.
ctx.request
- return
FaaSHTTPRequest
HTTP Request object simulated by FaaS.
ctx.response
- return
FaaSHTTPResponse
HTTP Response object simulated by FaaS.