@midwayjs/fc-starter 3.4.0-beta.7 → 3.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1,7 +1,8 @@
1
- import type { ServerlessStarterOptions } from '@midwayjs/faas';
2
- export declare class BootstrapStarter {
3
- applicationContext: any;
4
- start(options?: ServerlessStarterOptions): {};
5
- getApplicationContext(): any;
1
+ import { AbstractBootstrapStarter, FC } from '@midwayjs/faas';
2
+ export declare class BootstrapStarter extends AbstractBootstrapStarter {
3
+ onStart(): {};
4
+ onInit(context: FC.InitializeContext, exports: any): Promise<void>;
5
+ onRequest(event: any, context: any, oldContext: any): Promise<any>;
6
+ onClose(): Promise<void>;
6
7
  }
7
8
  //# sourceMappingURL=index.d.ts.map
package/dist/index.js CHANGED
@@ -2,14 +2,16 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.BootstrapStarter = void 0;
4
4
  const core_1 = require("@midwayjs/core");
5
+ const faas_1 = require("@midwayjs/faas");
5
6
  const getRawBody = require("raw-body");
7
+ const async_hooks_context_manager_1 = require("@midwayjs/async-hooks-context-manager");
6
8
  function isOutputError() {
7
9
  return (process.env.SERVERLESS_OUTPUT_ERROR_STACK === 'true' ||
8
10
  ['local', 'development'].includes(process.env.MIDWAY_SERVER_ENV) ||
9
11
  ['local', 'development'].includes(process.env.NODE_ENV));
10
12
  }
11
- class BootstrapStarter {
12
- start(options = {}) {
13
+ class BootstrapStarter extends faas_1.AbstractBootstrapStarter {
14
+ onStart() {
13
15
  if (!process.env.NODE_ENV) {
14
16
  process.env.NODE_ENV = 'production';
15
17
  }
@@ -20,180 +22,185 @@ class BootstrapStarter {
20
22
  process.env['MIDWAY_LOGGER_DISABLE_COLORS'] = 'true';
21
23
  }
22
24
  const exports = {};
23
- let framework;
24
- exports[options.initializeMethodName || 'initializer'] = (0, core_1.wrapAsync)(async (context) => {
25
- var _a, _b, _c;
26
- const applicationAdapter = {
27
- getFunctionName() {
28
- return context.function.name;
29
- },
30
- getFunctionServiceName() {
31
- return context.service.name;
25
+ exports[this.options.initializeMethodName || 'initializer'] = (0, core_1.wrapAsync)(async (context) => {
26
+ await this.onInit(context, exports);
27
+ });
28
+ if (this.options.handlerName) {
29
+ exports[this.options.handlerName.split('.')[1]] = (0, core_1.wrapAsync)(this.onRequest.bind(this));
30
+ }
31
+ if (this.options.aggregationHandlerName) {
32
+ exports[this.options.aggregationHandlerName.split('.')[1]] = (0, core_1.wrapAsync)(this.onRequest.bind(this));
33
+ }
34
+ return exports;
35
+ }
36
+ async onInit(context, exports) {
37
+ const applicationAdapter = {
38
+ getFunctionName() {
39
+ return context.function.name;
40
+ },
41
+ getFunctionServiceName() {
42
+ return context.service.name;
43
+ },
44
+ };
45
+ await this.initFramework({
46
+ globalConfig: {
47
+ faas: {
48
+ applicationAdapter,
32
49
  },
50
+ },
51
+ asyncContextManager: (0, async_hooks_context_manager_1.createContextManager)(),
52
+ ...this.options,
53
+ });
54
+ const handlerWrapper = (0, core_1.wrapAsync)(this.onRequest.bind(this));
55
+ for (const handlerName of this.framework.getAllHandlerNames()) {
56
+ exports[handlerName.split('.')[1]] = handlerWrapper;
57
+ }
58
+ }
59
+ async onRequest(event, context, oldContext) {
60
+ var _a, _b, _c, _d;
61
+ const isHTTPMode = event.constructor.name === 'IncomingMessage' ||
62
+ event.constructor.name === 'EventEmitter';
63
+ const isApiGateway = event &&
64
+ event.headers &&
65
+ 'queryParameters' in event &&
66
+ 'httpMethod' in event;
67
+ if (isHTTPMode) {
68
+ if (!((_a = oldContext.logger) === null || _a === void 0 ? void 0 : _a.info)) {
69
+ oldContext.logger = console;
70
+ }
71
+ }
72
+ else {
73
+ if (!((_b = context.logger) === null || _b === void 0 ? void 0 : _b.info)) {
74
+ context.logger = console;
75
+ }
76
+ }
77
+ let ctx;
78
+ if (isHTTPMode) {
79
+ event.getOriginContext = () => {
80
+ return oldContext;
33
81
  };
34
- (_a = options.performance) === null || _a === void 0 ? void 0 : _a.mark('starterRuntimeStartTime');
35
- // init midway
36
- const applicationContext = (this.applicationContext =
37
- await (0, core_1.initializeGlobalApplicationContext)(Object.assign(options, {
38
- globalConfig: {
39
- faas: {
40
- applicationAdapter,
41
- },
42
- },
43
- })));
44
- (_b = options.performance) === null || _b === void 0 ? void 0 : _b.mark('frameworkStartTime');
45
- const midwayFrameworkService = applicationContext.get(core_1.MidwayFrameworkService);
46
- framework = midwayFrameworkService.getMainFramework();
47
- const handlerWrapper = (0, core_1.wrapAsync)(async (event, context, oldContext) => {
48
- var _a, _b, _c, _d;
49
- const isHTTPMode = event.constructor.name === 'IncomingMessage' ||
50
- event.constructor.name === 'EventEmitter';
51
- const isApiGateway = event &&
52
- event.headers &&
53
- 'queryParameters' in event &&
54
- 'httpMethod' in event;
55
- if (isHTTPMode) {
56
- if (!((_a = oldContext.logger) === null || _a === void 0 ? void 0 : _a.info)) {
57
- oldContext.logger = console;
58
- }
59
- }
60
- else {
61
- if (!((_b = context.logger) === null || _b === void 0 ? void 0 : _b.info)) {
62
- context.logger = console;
63
- }
64
- }
65
- const triggerFunction = framework.getTriggerFunction((oldContext === null || oldContext === void 0 ? void 0 : oldContext.function.handler) || context.function.handler);
66
- let ctx;
67
- if (isHTTPMode) {
68
- event.getOriginContext = () => {
69
- return oldContext;
70
- };
71
- // 如果需要解析body并且body是个stream
72
- if (['post', 'put', 'delete'].indexOf(event.method.toLowerCase()) !==
73
- -1 &&
74
- !event.body &&
75
- typeof event.on === 'function') {
76
- event.body = await getRawBody(event, {
77
- limit: '10mb',
78
- });
79
- }
80
- ctx = await framework.wrapHttpRequest(event);
81
- }
82
- else if (isApiGateway) {
83
- ctx = await framework.wrapHttpRequest(event, context);
82
+ // 如果需要解析body并且body是个stream
83
+ if (['post', 'put', 'delete'].indexOf(event.method.toLowerCase()) !== -1 &&
84
+ !event.body &&
85
+ typeof event.on === 'function') {
86
+ event.body = await getRawBody(event, {
87
+ limit: '10mb',
88
+ });
89
+ }
90
+ ctx = await this.framework.wrapHttpRequest(event);
91
+ }
92
+ else if (isApiGateway) {
93
+ ctx = await this.framework.wrapHttpRequest(event, context);
94
+ }
95
+ else {
96
+ // 阿里云事件触发器,入参是 buffer
97
+ if (Buffer.isBuffer(event)) {
98
+ event = event.toString('utf8');
99
+ try {
100
+ event = JSON.parse(event);
84
101
  }
85
- else {
86
- // 阿里云事件触发器,入参是 buffer
87
- if (Buffer.isBuffer(event)) {
88
- event = event.toString('utf8');
89
- try {
90
- event = JSON.parse(event);
91
- }
92
- catch (_err) {
93
- /** ignore */
94
- }
95
- }
96
- // format context
97
- ctx = {
98
- originEvent: event,
99
- originContext: context,
100
- logger: context.logger,
101
- };
102
+ catch (_err) {
103
+ /** ignore */
102
104
  }
103
- try {
104
- const result = await triggerFunction(ctx, {
105
- isHttpFunction: isHTTPMode || isApiGateway,
106
- originEvent: event,
107
- originContext: context,
108
- });
109
- if (isHTTPMode || isApiGateway) {
110
- const { isBase64Encoded, statusCode, headers, body } = result;
111
- if (isApiGateway) {
112
- const newHeader = {};
113
- for (const key in headers) {
114
- // The length after base64 is wrong.
115
- if (!['content-length'].includes(key)) {
116
- if ('set-cookie' === key && !isHTTPMode) {
117
- // unsupport multiple cookie when use apiGateway
118
- newHeader[key] = headers[key][0];
119
- if (headers[key].length > 1) {
120
- ctx.logger.warn('[fc-starter]: unsupport multiple cookie when use apiGateway');
121
- }
122
- }
123
- else {
124
- newHeader[key] = headers[key];
125
- }
126
- }
127
- }
128
- return {
129
- isBase64Encoded,
130
- statusCode,
131
- headers: newHeader,
132
- body,
133
- };
134
- }
135
- else {
136
- const res = context;
137
- if (res.headersSent) {
138
- return;
139
- }
140
- if (res.setHeader) {
141
- for (const key in headers) {
142
- res.setHeader(key, headers[key]);
143
- }
144
- }
145
- if (res.statusCode !== statusCode) {
146
- if (res.setStatusCode) {
147
- res.setStatusCode(statusCode);
148
- }
149
- if (res.statusCode) {
150
- res.statusCode = statusCode;
105
+ }
106
+ // format context
107
+ ctx = {
108
+ originEvent: event,
109
+ originContext: context,
110
+ logger: context.logger,
111
+ };
112
+ }
113
+ let handlerName = (oldContext === null || oldContext === void 0 ? void 0 : oldContext.function.handler) || context.function.handler;
114
+ // 聚合部署的情况
115
+ if (this.options.aggregationHandlerName) {
116
+ if (this.options.handlerNameMapping) {
117
+ [handlerName, event, context, oldContext] =
118
+ this.options.handlerNameMapping(handlerName, event, context, oldContext);
119
+ }
120
+ else if (isHTTPMode) {
121
+ handlerName = ctx.path;
122
+ }
123
+ }
124
+ const triggerFunction = this.framework.getTriggerFunction(handlerName);
125
+ try {
126
+ const result = await triggerFunction(ctx, {
127
+ isHttpFunction: isHTTPMode || isApiGateway,
128
+ originEvent: event,
129
+ originContext: context,
130
+ });
131
+ if (isHTTPMode || isApiGateway) {
132
+ const { isBase64Encoded, statusCode, headers, body } = result;
133
+ if (isApiGateway) {
134
+ const newHeader = {};
135
+ for (const key in headers) {
136
+ // The length after base64 is wrong.
137
+ if (!['content-length'].includes(key)) {
138
+ if ('set-cookie' === key && !isHTTPMode) {
139
+ // unsupport multiple cookie when use apiGateway
140
+ newHeader[key] = headers[key][0];
141
+ if (headers[key].length > 1) {
142
+ ctx.logger.warn('[fc-starter]: unsupport multiple cookie when use apiGateway');
151
143
  }
152
144
  }
153
- if (res.send) {
154
- // http trigger only support `Buffer` or a `string` or a `stream.Readable`
155
- res.send(body);
145
+ else {
146
+ newHeader[key] = headers[key];
156
147
  }
157
148
  }
158
149
  }
159
- else {
160
- return result;
161
- }
150
+ return {
151
+ isBase64Encoded,
152
+ statusCode,
153
+ headers: newHeader,
154
+ body,
155
+ };
162
156
  }
163
- catch (err) {
164
- ctx.logger.error(err);
157
+ else {
165
158
  const res = context;
159
+ if (res.headersSent) {
160
+ return;
161
+ }
166
162
  if (res.setHeader) {
167
- res.setHeader('content-type', 'text/plain');
163
+ for (const key in headers) {
164
+ res.setHeader(key, headers[key]);
165
+ }
166
+ }
167
+ if (res.statusCode !== statusCode) {
168
+ if (res.setStatusCode) {
169
+ res.setStatusCode(statusCode);
170
+ }
171
+ if (res.statusCode) {
172
+ res.statusCode = statusCode;
173
+ }
168
174
  }
169
175
  if (res.send) {
170
- res.setStatusCode((_c = err.status) !== null && _c !== void 0 ? _c : 500);
171
- res.send(isOutputError() ? err.stack : 'Internal Server Error');
176
+ // http trigger only support `Buffer` or a `string` or a `stream.Readable`
177
+ res.send(body);
172
178
  }
173
- return {
174
- isBase64Encoded: false,
175
- statusCode: (_d = err.status) !== null && _d !== void 0 ? _d : 500,
176
- headers: {},
177
- body: isOutputError() ? err.stack : 'Internal Server Error',
178
- };
179
- }
180
- });
181
- if (options.exportAllHandler) {
182
- for (const handlerName of framework.getAllHandlerNames()) {
183
- exports[handlerName.split('.')[1]] = handlerWrapper;
184
179
  }
185
180
  }
186
181
  else {
187
- const handlerMethodName = context.function.handler.split('.')[1];
188
- exports[handlerMethodName] = handlerWrapper;
182
+ return result;
189
183
  }
190
- (_c = options.performance) === null || _c === void 0 ? void 0 : _c.end();
191
- });
192
- return exports;
193
- }
194
- getApplicationContext() {
195
- return this.applicationContext;
184
+ }
185
+ catch (err) {
186
+ ctx.logger.error(err);
187
+ const res = context;
188
+ if (res.setHeader) {
189
+ res.setHeader('content-type', 'text/plain');
190
+ }
191
+ if (res.send) {
192
+ res.setStatusCode((_c = err.status) !== null && _c !== void 0 ? _c : 500);
193
+ res.send(isOutputError() ? err.stack : 'Internal Server Error');
194
+ }
195
+ return {
196
+ isBase64Encoded: false,
197
+ statusCode: (_d = err.status) !== null && _d !== void 0 ? _d : 500,
198
+ headers: {},
199
+ body: isOutputError() ? err.stack : 'Internal Server Error',
200
+ };
201
+ }
196
202
  }
203
+ async onClose() { }
197
204
  }
198
205
  exports.BootstrapStarter = BootstrapStarter;
199
206
  //# sourceMappingURL=index.js.map
package/package.json CHANGED
@@ -1,17 +1,18 @@
1
1
  {
2
2
  "name": "@midwayjs/fc-starter",
3
- "version": "3.4.0-beta.7",
3
+ "version": "3.4.0",
4
4
  "main": "dist/index",
5
5
  "typings": "dist/index.d.ts",
6
6
  "dependencies": {
7
- "@midwayjs/faas": "^3.4.0-beta.7",
7
+ "@midwayjs/async-hooks-context-manager": "^3.4.0",
8
+ "@midwayjs/faas": "^3.4.0",
8
9
  "raw-body": "2.5.1"
9
10
  },
10
11
  "devDependencies": {
11
- "@midwayjs/core": "^3.4.0-beta.7",
12
- "@midwayjs/decorator": "^3.4.0-beta.7",
13
- "@midwayjs/runtime-mock": "^3.4.0-beta.7",
14
- "@midwayjs/serverless-http-parser": "^3.4.0-beta.7"
12
+ "@midwayjs/core": "^3.4.0",
13
+ "@midwayjs/decorator": "^3.4.0",
14
+ "@midwayjs/runtime-mock": "^3.4.0",
15
+ "@midwayjs/serverless-http-parser": "^3.4.0"
15
16
  },
16
17
  "engines": {
17
18
  "node": ">=12"
@@ -30,5 +31,5 @@
30
31
  "url": "git@github.com:midwayjs/midway.git"
31
32
  },
32
33
  "license": "MIT",
33
- "gitHead": "4d5cc59a7a33e49beeaf20fcfaf766438649959c"
34
+ "gitHead": "e48ea9cb52c6e70ab25b68f1188006100eab8184"
34
35
  }