@midwayjs/faas 3.3.6-beta.5 → 3.4.0-beta.11

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2013 - Now midwayjs
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -1,7 +1,7 @@
1
1
  export declare const midwayLogger: {
2
2
  default: {
3
- disableFile: boolean;
4
- disableError: boolean;
3
+ enableFile: boolean;
4
+ enableError: boolean;
5
5
  printFormat: (info: any) => string;
6
6
  };
7
7
  };
@@ -3,8 +3,8 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.midwayLogger = void 0;
4
4
  exports.midwayLogger = {
5
5
  default: {
6
- disableFile: true,
7
- disableError: true,
6
+ enableFile: false,
7
+ enableError: false,
8
8
  printFormat: (info) => {
9
9
  var _a, _b, _c, _d, _e, _f;
10
10
  const requestId = (_f = (_c = (_b = (_a = info.ctx) === null || _a === void 0 ? void 0 : _a['originContext']) === null || _b === void 0 ? void 0 : _b['requestId']) !== null && _c !== void 0 ? _c : (_e = (_d = info.ctx) === null || _d === void 0 ? void 0 : _d['originContext']) === null || _e === void 0 ? void 0 : _e['request_id']) !== null && _f !== void 0 ? _f : '';
@@ -33,8 +33,10 @@ let FaaSConfiguration = class FaaSConfiguration {
33
33
  async onReady(container) { }
34
34
  async onServerReady() {
35
35
  if (!this.framework.isEnable()) {
36
+ // just in legacy local dev and test
36
37
  await this.framework.run();
37
38
  }
39
+ await this.framework.loadFunction();
38
40
  }
39
41
  };
40
42
  __decorate([
@@ -1,5 +1,5 @@
1
1
  /// <reference types="node" />
2
- import { Context, IFaaSConfigurationOptions, Application, NextFunction } from './interface';
2
+ import { Context, IFaaSConfigurationOptions, Application, NextFunction, HandlerOptions } from './interface';
3
3
  import { BaseFramework, CommonMiddlewareUnion, ContextMiddlewareManager, FunctionMiddleware, IMidwayBootstrapOptions, MidwayEnvironmentService, MidwayFrameworkType, MidwayMiddlewareService, RouterInfo } from '@midwayjs/core';
4
4
  import { LoggerOptions } from '@midwayjs/logger';
5
5
  import * as http from 'http';
@@ -11,28 +11,29 @@ export declare class MidwayFaaSFramework extends BaseFramework<Application, Cont
11
11
  app: Application;
12
12
  private isReplaceLogger;
13
13
  private developmentRun;
14
- private serverlessRoutes;
15
14
  private server;
16
15
  private respond;
17
16
  private applicationAdapter;
17
+ private serverlessFunctionService;
18
18
  protected httpMiddlewareManager: ContextMiddlewareManager<Context, unknown, unknown>;
19
19
  protected eventMiddlewareManager: ContextMiddlewareManager<Context, unknown, unknown>;
20
+ private legacyVersion;
21
+ private loadedFunction;
20
22
  environmentService: MidwayEnvironmentService;
21
23
  middlewareService: MidwayMiddlewareService<Context, any>;
22
24
  configure(options: IFaaSConfigurationOptions): any;
23
25
  isEnable(): boolean;
24
26
  applicationInitialize(options: IMidwayBootstrapOptions): Promise<void>;
25
27
  run(): Promise<void>;
28
+ loadFunction(): Promise<void>;
26
29
  getFrameworkType(): MidwayFrameworkType;
27
- handleInvokeWrapper(handlerMapping: string): (...args: any[]) => Promise<{
28
- result: any;
29
- error: Error;
30
- } | {
31
- isBase64Encoded: boolean;
32
- statusCode: any;
33
- headers: any;
34
- body: any;
35
- }>;
30
+ /**
31
+ * @deprecated
32
+ * @param handlerMapping
33
+ */
34
+ handleInvokeWrapper(handlerMapping: string): (...args: any[]) => Promise<any>;
35
+ getTriggerFunction(handlerMapping: string): (context: any, options: HandlerOptions) => Promise<any>;
36
+ wrapHttpRequest(req: http.IncomingMessage | Record<string, any>, res?: http.ServerResponse): Promise<unknown>;
36
37
  /**
37
38
  * @deprecated
38
39
  * @param middlewareId
@@ -44,10 +45,11 @@ export declare class MidwayFaaSFramework extends BaseFramework<Application, Cont
44
45
  createLogger(name: string, option?: LoggerOptions): import("@midwayjs/core").ILogger;
45
46
  getFrameworkName(): string;
46
47
  getServer(): http.Server;
48
+ beforeStop(): Promise<void>;
47
49
  protected createHttpContext(req: any, res: any): Promise<unknown>;
48
50
  useMiddleware(middleware: CommonMiddlewareUnion<Context, NextFunction, undefined>): void;
49
51
  useEventMiddleware(middleware: CommonMiddlewareUnion<Context, NextFunction, undefined>): void;
50
52
  getEventMiddleware(): ContextMiddlewareManager<Context, NextFunction, undefined>;
53
+ getAllHandlerNames(): string[];
51
54
  }
52
- export declare const createModuleServerlessFramework: (globalOption: Omit<IMidwayBootstrapOptions, 'applicationContext'> & IFaaSConfigurationOptions) => Promise<MidwayFaaSFramework>;
53
55
  //# sourceMappingURL=framework.d.ts.map
package/dist/framework.js CHANGED
@@ -9,13 +9,14 @@ var __metadata = (this && this.__metadata) || function (k, v) {
9
9
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
10
  };
11
11
  Object.defineProperty(exports, "__esModule", { value: true });
12
- exports.createModuleServerlessFramework = exports.MidwayFaaSFramework = void 0;
12
+ exports.MidwayFaaSFramework = void 0;
13
13
  const core_1 = require("@midwayjs/core");
14
14
  const decorator_1 = require("@midwayjs/decorator");
15
15
  const simple_lock_1 = require("@midwayjs/simple-lock");
16
16
  const logger_1 = require("@midwayjs/logger");
17
17
  const serverless_http_parser_1 = require("@midwayjs/serverless-http-parser");
18
- const http = require("http");
18
+ const util_1 = require("util");
19
+ const { isAnyArrayBuffer, isUint8Array } = util_1.types;
19
20
  const LOCK_KEY = '_faas_starter_start_key';
20
21
  let MidwayFaaSFramework = class MidwayFaaSFramework extends core_1.BaseFramework {
21
22
  constructor() {
@@ -25,9 +26,10 @@ let MidwayFaaSFramework = class MidwayFaaSFramework extends core_1.BaseFramework
25
26
  this.lock = new simple_lock_1.default();
26
27
  this.isReplaceLogger = process.env['MIDWAY_SERVERLESS_REPLACE_LOGGER'] === 'true';
27
28
  this.developmentRun = false;
28
- this.serverlessRoutes = [];
29
29
  this.httpMiddlewareManager = this.createMiddlewareManager();
30
30
  this.eventMiddlewareManager = this.createMiddlewareManager();
31
+ this.legacyVersion = false;
32
+ this.loadedFunction = false;
31
33
  }
32
34
  configure(options) {
33
35
  var _a;
@@ -48,7 +50,11 @@ let MidwayFaaSFramework = class MidwayFaaSFramework extends core_1.BaseFramework
48
50
  if (!this.logger) {
49
51
  this.logger = options.logger || logger_1.loggers.getLogger('appLogger');
50
52
  }
51
- this.applicationAdapter = this.configurationOptions.applicationAdapter;
53
+ this.applicationAdapter =
54
+ this.configurationOptions.applicationAdapter || {};
55
+ if (this.applicationAdapter.getApplication) {
56
+ this.legacyVersion = true;
57
+ }
52
58
  this.app =
53
59
  ((_b = (_a = this.applicationAdapter).getApplication) === null || _b === void 0 ? void 0 : _b.call(_a)) ||
54
60
  new serverless_http_parser_1.Application();
@@ -68,13 +74,33 @@ let MidwayFaaSFramework = class MidwayFaaSFramework extends core_1.BaseFramework
68
74
  },
69
75
  getFunctionName: () => {
70
76
  var _a;
71
- return (_a = this.configurationOptions.applicationAdapter) === null || _a === void 0 ? void 0 : _a.getFunctionName();
77
+ return (process.env.MIDWAY_SERVERLESS_FUNCTION_NAME ||
78
+ ((_a = this.configurationOptions.applicationAdapter) === null || _a === void 0 ? void 0 : _a.getFunctionName()) ||
79
+ '');
72
80
  },
81
+ /**
82
+ * get function service/group in runtime
83
+ */
73
84
  getFunctionServiceName: () => {
74
85
  var _a;
75
- return (_a = this.configurationOptions.applicationAdapter) === null || _a === void 0 ? void 0 : _a.getFunctionServiceName();
86
+ return (process.env.MIDWAY_SERVERLESS_SERVICE_NAME ||
87
+ ((_a = this.configurationOptions.applicationAdapter) === null || _a === void 0 ? void 0 : _a.getFunctionServiceName()) ||
88
+ '');
89
+ },
90
+ useEventMiddleware: middleware => {
91
+ return this.useEventMiddleware(middleware);
92
+ },
93
+ getEventMiddleware: () => {
94
+ return this.getEventMiddleware();
95
+ },
96
+ getServerlessInstance: (serviceClass) => {
97
+ return this.app
98
+ .createAnonymousContext()
99
+ .requestContext.getAsync(serviceClass);
100
+ },
101
+ getTriggerFunction: (handlerMapping) => {
102
+ return this.getTriggerFunction(handlerMapping);
76
103
  },
77
- useEventMiddleware: () => { },
78
104
  });
79
105
  // hack use method
80
106
  this.app.originUse = this.app.use;
@@ -84,80 +110,96 @@ let MidwayFaaSFramework = class MidwayFaaSFramework extends core_1.BaseFramework
84
110
  }
85
111
  }
86
112
  async run() {
87
- return this.lock.sureOnce(async () => {
88
- var _a, _b;
89
- // set app keys
90
- this.app['keys'] = (_a = this.configService.getConfiguration('keys')) !== null && _a !== void 0 ? _a : '';
91
- // store all http function entry
92
- const collector = new core_1.ServerlessTriggerCollector();
93
- const functionList = await collector.getFunctionList();
94
- for (const funcInfo of functionList) {
95
- // store handler
96
- this.funMappingStore.set(funcInfo.funcHandlerName, funcInfo);
97
- if (funcInfo.url) {
98
- // store router
99
- this.serverlessRoutes.push({
100
- matchPattern: (0, core_1.pathToRegexp)(funcInfo.url, [], { end: false }),
101
- funcInfo: funcInfo,
102
- });
113
+ if (this.legacyVersion) {
114
+ return this.loadFunction();
115
+ }
116
+ }
117
+ async loadFunction() {
118
+ if (!this.loadedFunction) {
119
+ this.loadedFunction = true;
120
+ return this.lock.sureOnce(async () => {
121
+ var _a;
122
+ // set app keys
123
+ this.app['keys'] = (_a = this.configService.getConfiguration('keys')) !== null && _a !== void 0 ? _a : '';
124
+ // store all http function entry
125
+ this.serverlessFunctionService = await this.applicationContext.getAsync(core_1.MidwayServerlessFunctionService);
126
+ const functionList = await this.serverlessFunctionService.getFunctionList();
127
+ for (const funcInfo of functionList) {
128
+ // store handler
129
+ this.funMappingStore.set(funcInfo.funcHandlerName, funcInfo);
103
130
  }
104
- }
105
- this.respond = this.app.callback();
106
- if (this.environmentService.isDevelopmentEnvironment()) {
107
- const faasConfig = (_b = this.configService.getConfiguration('faas')) !== null && _b !== void 0 ? _b : {};
108
- this.server = await new Promise(resolve => {
109
- const server = http.createServer((req, res) => {
110
- const url = new URL(req.url, `http://${req.headers.host}`);
111
- // create event and invoke
112
- this.handleInvokeWrapper(url.pathname)(req, res, {});
113
- });
114
- if (faasConfig['port']) {
115
- server.listen(faasConfig['port']);
116
- }
117
- resolve(server);
118
- });
119
- }
120
- }, LOCK_KEY);
131
+ this.respond = this.app.callback();
132
+ }, LOCK_KEY);
133
+ }
121
134
  }
122
135
  getFrameworkType() {
123
136
  return core_1.MidwayFrameworkType.FAAS;
124
137
  }
138
+ /**
139
+ * @deprecated
140
+ * @param handlerMapping
141
+ */
125
142
  handleInvokeWrapper(handlerMapping) {
126
- let funOptions = this.funMappingStore.get(handlerMapping);
143
+ const funOptions = this.funMappingStore.get(handlerMapping);
127
144
  return async (...args) => {
128
- var _a, _b;
129
145
  if (args.length === 0) {
130
146
  throw new Error('first parameter must be function context');
131
147
  }
132
- const event = args[0];
133
- const isLegacyMode = event.originContext && event.originEvent;
134
- const isHttpFunction = event.constructor.name === 'IncomingMessage' ||
135
- event.constructor.name === 'EventEmitter' ||
136
- !!(event.headers && event.get);
148
+ if (!funOptions) {
149
+ throw new Error(`function handler = ${handlerMapping} not found`);
150
+ }
151
+ const context = this.getContext(args.shift());
152
+ const isHttpFunction = !!(context.headers && context.get);
153
+ const globalMiddlewareFn = await this.applyMiddleware();
154
+ const middlewareManager = new core_1.ContextMiddlewareManager();
155
+ middlewareManager.insertLast(globalMiddlewareFn);
156
+ middlewareManager.insertLast(async (ctx, next) => {
157
+ const fn = await this.middlewareService.compose([
158
+ ...(isHttpFunction
159
+ ? this.httpMiddlewareManager
160
+ : this.eventMiddlewareManager),
161
+ ...funOptions.controllerMiddleware,
162
+ ...funOptions.middleware,
163
+ async (ctx, next) => {
164
+ if (isHttpFunction) {
165
+ args = [ctx];
166
+ }
167
+ // invoke handler
168
+ const result = await this.invokeHandler(funOptions, ctx, args, isHttpFunction);
169
+ if (isHttpFunction && result !== undefined) {
170
+ if (result === null) {
171
+ // 这样设置可以绕过 koa 的 _explicitStatus 赋值机制
172
+ ctx.response._body = null;
173
+ }
174
+ else {
175
+ ctx.body = result;
176
+ }
177
+ }
178
+ return result;
179
+ },
180
+ ], this.app);
181
+ return await fn(ctx, next);
182
+ });
183
+ const composeMiddleware = await this.middlewareService.compose(middlewareManager, this.app);
184
+ return await composeMiddleware(context);
185
+ };
186
+ }
187
+ getTriggerFunction(handlerMapping) {
188
+ let funOptions = this.funMappingStore.get(handlerMapping);
189
+ return async (context, options) => {
190
+ var _a;
191
+ const isHttpFunction = options.isHttpFunction;
137
192
  if (!funOptions && isHttpFunction) {
138
- for (const item of this.serverlessRoutes) {
139
- if (item.matchPattern.test(event.path)) {
140
- funOptions = item.funcInfo;
141
- break;
142
- }
193
+ funOptions = await this.serverlessFunctionService.getMatchedRouterInfo(context.path, context.method);
194
+ if (funOptions) {
195
+ const matchRes = core_1.PathToRegexpUtil.match(funOptions.fullUrlFlattenString)(context.path);
196
+ context.req.pathParameters = matchRes['params'] || {};
143
197
  }
144
198
  }
145
199
  if (!funOptions) {
146
200
  throw new Error(`function handler = ${handlerMapping} not found`);
147
201
  }
148
- let context;
149
- if (isLegacyMode) {
150
- context = this.getContext(args.shift());
151
- }
152
- else if (isHttpFunction) {
153
- const newReq = ((_a = this.applicationAdapter) === null || _a === void 0 ? void 0 : _a.runRequestHook(...args)) ||
154
- new serverless_http_parser_1.HTTPRequest(args[0], args[1]);
155
- const newRes = new serverless_http_parser_1.HTTPResponse();
156
- context = this.getContext(await this.createHttpContext(newReq, newRes));
157
- }
158
- else {
159
- context = this.getContext(await ((_b = this.applicationAdapter) === null || _b === void 0 ? void 0 : _b.runEventHook(...args)));
160
- }
202
+ context = this.getContext(context);
161
203
  const result = await (await this.applyMiddleware(async (ctx, next) => {
162
204
  const fn = await this.middlewareService.compose([
163
205
  ...(isHttpFunction
@@ -166,24 +208,34 @@ let MidwayFaaSFramework = class MidwayFaaSFramework extends core_1.BaseFramework
166
208
  ...funOptions.controllerMiddleware,
167
209
  ...funOptions.middleware,
168
210
  async (ctx, next) => {
211
+ let args;
169
212
  if (isHttpFunction) {
170
213
  args = [ctx];
171
214
  }
215
+ else {
216
+ args = [options.originEvent, options.originContext];
217
+ }
172
218
  // invoke handler
173
219
  const result = await this.invokeHandler(funOptions, ctx, args, isHttpFunction);
174
220
  if (isHttpFunction && result !== undefined) {
175
- ctx.body = result;
221
+ if (result === null) {
222
+ // 这样设置可以绕过 koa 的 _explicitStatus 赋值机制
223
+ ctx.response._body = null;
224
+ }
225
+ else {
226
+ ctx.body = result;
227
+ }
228
+ }
229
+ // http 靠 ctx.body,否则会出现状态码不正确的问题
230
+ if (!isHttpFunction) {
231
+ return result;
176
232
  }
177
- return result;
178
233
  },
179
234
  ], this.app);
180
235
  return await fn(ctx, next);
181
236
  }))(context);
182
- if (isLegacyMode) {
183
- return result;
184
- }
185
- else if (isHttpFunction) {
186
- if (!context.response._explicitStatus) {
237
+ if (isHttpFunction) {
238
+ if (!((_a = context.response) === null || _a === void 0 ? void 0 : _a._explicitStatus)) {
187
239
  if (context.body === null || context.body === 'undefined') {
188
240
  context.body = '';
189
241
  context.type = 'text';
@@ -198,13 +250,13 @@ let MidwayFaaSFramework = class MidwayFaaSFramework extends core_1.BaseFramework
198
250
  }
199
251
  context.body = data;
200
252
  }
201
- else if (Buffer.isBuffer(data)) {
253
+ else if (isAnyArrayBuffer(data) || isUint8Array(data)) {
202
254
  encoded = true;
203
255
  if (!context.type) {
204
256
  context.type = 'application/octet-stream';
205
257
  }
206
258
  // data is reserved as buffer
207
- context.body = data.toString('base64');
259
+ context.body = Buffer.from(data).toString('base64');
208
260
  }
209
261
  else if (typeof data === 'object') {
210
262
  if (!context.type) {
@@ -220,6 +272,13 @@ let MidwayFaaSFramework = class MidwayFaaSFramework extends core_1.BaseFramework
220
272
  // set data to string
221
273
  context.body = data = data + '';
222
274
  }
275
+ // middleware return value and will be got 204 status
276
+ if (context.body === undefined &&
277
+ !context.response._explicitStatus &&
278
+ context._matchedRoute) {
279
+ // 如果进了路由,重新赋值,防止 404
280
+ context.body = undefined;
281
+ }
223
282
  return {
224
283
  isBase64Encoded: encoded,
225
284
  statusCode: context.status,
@@ -232,6 +291,11 @@ let MidwayFaaSFramework = class MidwayFaaSFramework extends core_1.BaseFramework
232
291
  }
233
292
  };
234
293
  }
294
+ async wrapHttpRequest(req, res) {
295
+ const newReq = res ? new serverless_http_parser_1.HTTPRequest(req, res) : req;
296
+ const newRes = new serverless_http_parser_1.HTTPResponse();
297
+ return this.createHttpContext(newReq, newRes);
298
+ }
235
299
  /**
236
300
  * @deprecated
237
301
  * @param middlewareId
@@ -259,36 +323,44 @@ let MidwayFaaSFramework = class MidwayFaaSFramework extends core_1.BaseFramework
259
323
  return context;
260
324
  }
261
325
  async invokeHandler(routerInfo, context, args, isHttpFunction) {
262
- const funModule = await context.requestContext.getAsync(routerInfo.controllerId);
263
- const handlerName = this.getFunctionHandler(context, args, funModule, routerInfo.method) ||
264
- this.defaultHandlerMethod;
265
- if (funModule[handlerName]) {
266
- // invoke real method
267
- const result = await funModule[handlerName](...args);
268
- // implement response decorator
269
- const routerResponseData = routerInfo.responseMetadata;
270
- if (isHttpFunction) {
271
- for (const routerRes of routerResponseData) {
272
- switch (routerRes.type) {
273
- case decorator_1.WEB_RESPONSE_HTTP_CODE:
274
- context.status = routerRes.code;
275
- break;
276
- case decorator_1.WEB_RESPONSE_HEADER:
277
- for (const key in (routerRes === null || routerRes === void 0 ? void 0 : routerRes.setHeaders) || {}) {
278
- context.set(key, routerRes.setHeaders[key]);
279
- }
280
- break;
281
- case decorator_1.WEB_RESPONSE_CONTENT_TYPE:
282
- context.type = routerRes.contentType;
283
- break;
284
- case decorator_1.WEB_RESPONSE_REDIRECT:
285
- context.status = routerRes.code;
286
- context.redirect(routerRes.url);
287
- return;
326
+ if (typeof routerInfo.method !== 'string') {
327
+ if (!isHttpFunction) {
328
+ args.unshift(context);
329
+ }
330
+ return routerInfo.method(...args);
331
+ }
332
+ else {
333
+ const funModule = await context.requestContext.getAsync(routerInfo.controllerId);
334
+ const handlerName = this.getFunctionHandler(context, args, funModule, routerInfo.method) ||
335
+ this.defaultHandlerMethod;
336
+ if (funModule[handlerName]) {
337
+ // invoke real method
338
+ const result = await funModule[handlerName](...args);
339
+ // implement response decorator
340
+ const routerResponseData = routerInfo.responseMetadata;
341
+ if (isHttpFunction) {
342
+ for (const routerRes of routerResponseData) {
343
+ switch (routerRes.type) {
344
+ case decorator_1.WEB_RESPONSE_HTTP_CODE:
345
+ context.status = routerRes.code;
346
+ break;
347
+ case decorator_1.WEB_RESPONSE_HEADER:
348
+ for (const key in (routerRes === null || routerRes === void 0 ? void 0 : routerRes.setHeaders) || {}) {
349
+ context.set(key, routerRes.setHeaders[key]);
350
+ }
351
+ break;
352
+ case decorator_1.WEB_RESPONSE_CONTENT_TYPE:
353
+ context.type = routerRes.contentType;
354
+ break;
355
+ case decorator_1.WEB_RESPONSE_REDIRECT:
356
+ context.status = routerRes.code;
357
+ context.redirect(routerRes.url);
358
+ return;
359
+ }
288
360
  }
289
361
  }
362
+ return result;
290
363
  }
291
- return result;
292
364
  }
293
365
  }
294
366
  getFunctionHandler(ctx, args, target, method) {
@@ -311,6 +383,13 @@ let MidwayFaaSFramework = class MidwayFaaSFramework extends core_1.BaseFramework
311
383
  getServer() {
312
384
  return this.server;
313
385
  }
386
+ async beforeStop() {
387
+ if (this.server) {
388
+ new Promise(resolve => {
389
+ this.server.close(resolve);
390
+ });
391
+ }
392
+ }
314
393
  async createHttpContext(req, res) {
315
394
  return new Promise(resolve => {
316
395
  this.respond(req, res, resolve);
@@ -325,6 +404,9 @@ let MidwayFaaSFramework = class MidwayFaaSFramework extends core_1.BaseFramework
325
404
  getEventMiddleware() {
326
405
  return this.eventMiddlewareManager;
327
406
  }
407
+ getAllHandlerNames() {
408
+ return Array.from(this.funMappingStore.keys());
409
+ }
328
410
  };
329
411
  __decorate([
330
412
  (0, decorator_1.Inject)(),
@@ -338,13 +420,4 @@ MidwayFaaSFramework = __decorate([
338
420
  (0, decorator_1.Framework)()
339
421
  ], MidwayFaaSFramework);
340
422
  exports.MidwayFaaSFramework = MidwayFaaSFramework;
341
- const createModuleServerlessFramework = async (globalOption) => {
342
- const applicationContext = await (0, core_1.initializeGlobalApplicationContext)({
343
- ...globalOption,
344
- baseDir: '',
345
- appDir: '',
346
- });
347
- return applicationContext.get(MidwayFaaSFramework);
348
- };
349
- exports.createModuleServerlessFramework = createModuleServerlessFramework;
350
423
  //# sourceMappingURL=framework.js.map
package/dist/index.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  export * from './interface';
2
- export { MidwayFaaSFramework as Framework, createModuleServerlessFramework, } from './framework';
2
+ export { MidwayFaaSFramework as Framework } from './framework';
3
3
  export { FaaSConfiguration as Configuration } from './configuration';
4
+ export { AbstractBootstrapStarter } from './starter';
4
5
  //# sourceMappingURL=index.d.ts.map
package/dist/index.js CHANGED
@@ -14,11 +14,12 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
14
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
- exports.Configuration = exports.createModuleServerlessFramework = exports.Framework = void 0;
17
+ exports.AbstractBootstrapStarter = exports.Configuration = exports.Framework = void 0;
18
18
  __exportStar(require("./interface"), exports);
19
19
  var framework_1 = require("./framework");
20
20
  Object.defineProperty(exports, "Framework", { enumerable: true, get: function () { return framework_1.MidwayFaaSFramework; } });
21
- Object.defineProperty(exports, "createModuleServerlessFramework", { enumerable: true, get: function () { return framework_1.createModuleServerlessFramework; } });
22
21
  var configuration_1 = require("./configuration");
23
22
  Object.defineProperty(exports, "Configuration", { enumerable: true, get: function () { return configuration_1.FaaSConfiguration; } });
23
+ var starter_1 = require("./starter");
24
+ Object.defineProperty(exports, "AbstractBootstrapStarter", { enumerable: true, get: function () { return starter_1.AbstractBootstrapStarter; } });
24
25
  //# sourceMappingURL=index.js.map
@@ -1,4 +1,4 @@
1
- import { MidwayRequestContainer, IMidwayApplication, IConfigurationOptions, IMidwayContext, NextFunction as BaseNextFunction, CommonMiddlewareUnion, ContextMiddlewareManager } from '@midwayjs/core';
1
+ import { MidwayRequestContainer, IMidwayApplication, IConfigurationOptions, IMidwayContext, NextFunction as BaseNextFunction, CommonMiddlewareUnion, ContextMiddlewareManager, IMidwayBootstrapOptions } from '@midwayjs/core';
2
2
  import { FaaSHTTPContext } from '@midwayjs/faas-typings';
3
3
  import { ILogger } from '@midwayjs/logger';
4
4
  import { Application as ServerlessHttpApplication } from '@midwayjs/serverless-http-parser';
@@ -12,6 +12,11 @@ export interface FaaSContext extends IMidwayContext<FaaSHTTPContext> {
12
12
  * @deprecated
13
13
  */
14
14
  export declare type FaaSMiddleware = ((context: Context, next: () => Promise<any>) => any) | string;
15
+ export interface HandlerOptions {
16
+ isHttpFunction: boolean;
17
+ originEvent: any;
18
+ originContext: any;
19
+ }
15
20
  export declare type IMidwayFaaSApplication = IMidwayApplication<Context, {
16
21
  getInitializeContext(): any;
17
22
  use(middleware: FaaSMiddleware): any;
@@ -30,6 +35,8 @@ export declare type IMidwayFaaSApplication = IMidwayApplication<Context, {
30
35
  getFunctionServiceName(): string;
31
36
  useEventMiddleware(middleware: CommonMiddlewareUnion<Context, NextFunction, undefined>): void;
32
37
  getEventMiddleware: ContextMiddlewareManager<Context, NextFunction, undefined>;
38
+ getTriggerFunction(handler: string): (context: any, options: HandlerOptions) => Promise<any>;
39
+ getServerlessInstance<T>(serviceClass: T): Promise<T>;
33
40
  }> & ServerlessHttpApplication;
34
41
  export interface Application extends IMidwayFaaSApplication {
35
42
  }
@@ -40,12 +47,13 @@ export interface IFaaSConfigurationOptions extends IConfigurationOptions {
40
47
  config?: object;
41
48
  initializeContext?: object;
42
49
  applicationAdapter?: {
50
+ /**
51
+ * @deprecated
52
+ */
43
53
  getApplication(): Application;
44
54
  getFunctionName(): string;
45
55
  getFunctionServiceName(): string;
46
56
  runAppHook?(app: Application): void;
47
- runEventHook?(...args: any[]): any | void;
48
- runRequestHook?(...args: any[]): any | void;
49
57
  };
50
58
  }
51
59
  /**
@@ -54,4 +62,18 @@ export interface IFaaSConfigurationOptions extends IConfigurationOptions {
54
62
  export interface IWebMiddleware {
55
63
  resolve(): FaaSMiddleware;
56
64
  }
65
+ export interface ServerlessStarterOptions extends IMidwayBootstrapOptions {
66
+ initializeMethodName?: string;
67
+ handlerName?: string;
68
+ aggregationHandlerName?: string;
69
+ handlerNameMapping?: (handlerName: string, ...args: unknown[]) => [string, ...unknown[]];
70
+ createAdapter?: () => Promise<{
71
+ close(): any;
72
+ createAppHook(app?: any): any;
73
+ }>;
74
+ performance?: {
75
+ mark(label: string): any;
76
+ end(): any;
77
+ };
78
+ }
57
79
  //# sourceMappingURL=interface.d.ts.map
@@ -0,0 +1,17 @@
1
+ import { ServerlessStarterOptions } from './interface';
2
+ import { IMidwayBootstrapOptions } from '@midwayjs/core';
3
+ export declare abstract class AbstractBootstrapStarter {
4
+ protected options: ServerlessStarterOptions;
5
+ protected applicationContext: any;
6
+ protected framework: any;
7
+ constructor(options?: ServerlessStarterOptions);
8
+ getApplicationContext(): any;
9
+ close(): Promise<void>;
10
+ start(options?: ServerlessStarterOptions): any;
11
+ initFramework(bootstrapOptions?: IMidwayBootstrapOptions): Promise<void>;
12
+ abstract onStart(): any;
13
+ abstract onInit(...args: unknown[]): any;
14
+ abstract onRequest(...args: unknown[]): any;
15
+ abstract onClose(): any;
16
+ }
17
+ //# sourceMappingURL=starter.d.ts.map