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

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.
@@ -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 : '';
@@ -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';
@@ -24,7 +24,12 @@ export declare class MidwayFaaSFramework extends BaseFramework<Application, Cont
24
24
  applicationInitialize(options: IMidwayBootstrapOptions): Promise<void>;
25
25
  run(): Promise<void>;
26
26
  getFrameworkType(): MidwayFrameworkType;
27
- handleInvokeWrapper(handlerMapping: string): (...args: any[]) => Promise<{
27
+ /**
28
+ * @deprecated
29
+ * @param handlerMapping
30
+ */
31
+ handleInvokeWrapper(handlerMapping: string): (...args: any[]) => Promise<any>;
32
+ getTriggerFunction(handlerMapping: string): (context: any, options: HandlerOptions) => Promise<{
28
33
  result: any;
29
34
  error: Error;
30
35
  } | {
@@ -33,6 +38,7 @@ export declare class MidwayFaaSFramework extends BaseFramework<Application, Cont
33
38
  headers: any;
34
39
  body: any;
35
40
  }>;
41
+ wrapHttpRequest(req: http.IncomingMessage, res?: http.ServerResponse): Promise<unknown>;
36
42
  /**
37
43
  * @deprecated
38
44
  * @param middlewareId
@@ -48,6 +54,7 @@ export declare class MidwayFaaSFramework extends BaseFramework<Application, Cont
48
54
  useMiddleware(middleware: CommonMiddlewareUnion<Context, NextFunction, undefined>): void;
49
55
  useEventMiddleware(middleware: CommonMiddlewareUnion<Context, NextFunction, undefined>): void;
50
56
  getEventMiddleware(): ContextMiddlewareManager<Context, NextFunction, undefined>;
57
+ getAllHandlerNames(): string[];
51
58
  }
52
59
  export declare const createModuleServerlessFramework: (globalOption: Omit<IMidwayBootstrapOptions, 'applicationContext'> & IFaaSConfigurationOptions) => Promise<MidwayFaaSFramework>;
53
60
  //# sourceMappingURL=framework.d.ts.map
package/dist/framework.js CHANGED
@@ -15,7 +15,6 @@ 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");
19
18
  const LOCK_KEY = '_faas_starter_start_key';
20
19
  let MidwayFaaSFramework = class MidwayFaaSFramework extends core_1.BaseFramework {
21
20
  constructor() {
@@ -48,7 +47,8 @@ let MidwayFaaSFramework = class MidwayFaaSFramework extends core_1.BaseFramework
48
47
  if (!this.logger) {
49
48
  this.logger = options.logger || logger_1.loggers.getLogger('appLogger');
50
49
  }
51
- this.applicationAdapter = this.configurationOptions.applicationAdapter;
50
+ this.applicationAdapter =
51
+ this.configurationOptions.applicationAdapter || {};
52
52
  this.app =
53
53
  ((_b = (_a = this.applicationAdapter).getApplication) === null || _b === void 0 ? void 0 : _b.call(_a)) ||
54
54
  new serverless_http_parser_1.Application();
@@ -68,13 +68,33 @@ let MidwayFaaSFramework = class MidwayFaaSFramework extends core_1.BaseFramework
68
68
  },
69
69
  getFunctionName: () => {
70
70
  var _a;
71
- return (_a = this.configurationOptions.applicationAdapter) === null || _a === void 0 ? void 0 : _a.getFunctionName();
71
+ return (process.env.MIDWAY_SERVERLESS_FUNCTION_NAME ||
72
+ ((_a = this.configurationOptions.applicationAdapter) === null || _a === void 0 ? void 0 : _a.getFunctionName()) ||
73
+ '');
72
74
  },
75
+ /**
76
+ * get function service/group in runtime
77
+ */
73
78
  getFunctionServiceName: () => {
74
79
  var _a;
75
- return (_a = this.configurationOptions.applicationAdapter) === null || _a === void 0 ? void 0 : _a.getFunctionServiceName();
80
+ return (process.env.MIDWAY_SERVERLESS_SERVICE_NAME ||
81
+ ((_a = this.configurationOptions.applicationAdapter) === null || _a === void 0 ? void 0 : _a.getFunctionServiceName()) ||
82
+ '');
83
+ },
84
+ useEventMiddleware: middleware => {
85
+ return this.useEventMiddleware(middleware);
86
+ },
87
+ getEventMiddleware: () => {
88
+ return this.getEventMiddleware();
89
+ },
90
+ getServerlessInstance: (serviceClass) => {
91
+ return this.app
92
+ .createAnonymousContext()
93
+ .requestContext.getAsync(serviceClass);
94
+ },
95
+ getTriggerFunction: (handlerMapping) => {
96
+ return this.getTriggerFunction(handlerMapping);
76
97
  },
77
- useEventMiddleware: () => { },
78
98
  });
79
99
  // hack use method
80
100
  this.app.originUse = this.app.use;
@@ -85,7 +105,7 @@ let MidwayFaaSFramework = class MidwayFaaSFramework extends core_1.BaseFramework
85
105
  }
86
106
  async run() {
87
107
  return this.lock.sureOnce(async () => {
88
- var _a, _b;
108
+ var _a;
89
109
  // set app keys
90
110
  this.app['keys'] = (_a = this.configService.getConfiguration('keys')) !== null && _a !== void 0 ? _a : '';
91
111
  // store all http function entry
@@ -103,40 +123,63 @@ let MidwayFaaSFramework = class MidwayFaaSFramework extends core_1.BaseFramework
103
123
  }
104
124
  }
105
125
  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
126
  }, LOCK_KEY);
121
127
  }
122
128
  getFrameworkType() {
123
129
  return core_1.MidwayFrameworkType.FAAS;
124
130
  }
131
+ /**
132
+ * @deprecated
133
+ * @param handlerMapping
134
+ */
125
135
  handleInvokeWrapper(handlerMapping) {
126
- let funOptions = this.funMappingStore.get(handlerMapping);
136
+ const funOptions = this.funMappingStore.get(handlerMapping);
127
137
  return async (...args) => {
128
- var _a, _b;
129
138
  if (args.length === 0) {
130
139
  throw new Error('first parameter must be function context');
131
140
  }
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);
141
+ if (!funOptions) {
142
+ throw new Error(`function handler = ${handlerMapping} not found`);
143
+ }
144
+ const context = this.getContext(args.shift());
145
+ const isHttpFunction = !!(context.headers && context.get);
146
+ const globalMiddlewareFn = await this.applyMiddleware();
147
+ const middlewareManager = new core_1.ContextMiddlewareManager();
148
+ middlewareManager.insertLast(globalMiddlewareFn);
149
+ middlewareManager.insertLast(async (ctx, next) => {
150
+ const fn = await this.middlewareService.compose([
151
+ ...(isHttpFunction
152
+ ? this.httpMiddlewareManager
153
+ : this.eventMiddlewareManager),
154
+ ...funOptions.controllerMiddleware,
155
+ ...funOptions.middleware,
156
+ async (ctx, next) => {
157
+ if (isHttpFunction) {
158
+ args = [ctx];
159
+ }
160
+ // invoke handler
161
+ const result = await this.invokeHandler(funOptions, ctx, args, isHttpFunction);
162
+ if (isHttpFunction && result !== undefined) {
163
+ ctx.body = result;
164
+ }
165
+ return result;
166
+ },
167
+ ], this.app);
168
+ return await fn(ctx, next);
169
+ });
170
+ const composeMiddleware = await this.middlewareService.compose(middlewareManager, this.app);
171
+ return await composeMiddleware(context);
172
+ };
173
+ }
174
+ getTriggerFunction(handlerMapping) {
175
+ let funOptions = this.funMappingStore.get(handlerMapping);
176
+ return async (context, options) => {
177
+ var _a;
178
+ const isHttpFunction = options.isHttpFunction;
137
179
  if (!funOptions && isHttpFunction) {
138
180
  for (const item of this.serverlessRoutes) {
139
- if (item.matchPattern.test(event.path)) {
181
+ if (context.method === item.funcInfo['requestMethod'].toUpperCase() &&
182
+ item.matchPattern.test(context.path)) {
140
183
  funOptions = item.funcInfo;
141
184
  break;
142
185
  }
@@ -145,19 +188,7 @@ let MidwayFaaSFramework = class MidwayFaaSFramework extends core_1.BaseFramework
145
188
  if (!funOptions) {
146
189
  throw new Error(`function handler = ${handlerMapping} not found`);
147
190
  }
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
- }
191
+ context = this.getContext(context);
161
192
  const result = await (await this.applyMiddleware(async (ctx, next) => {
162
193
  const fn = await this.middlewareService.compose([
163
194
  ...(isHttpFunction
@@ -166,9 +197,13 @@ let MidwayFaaSFramework = class MidwayFaaSFramework extends core_1.BaseFramework
166
197
  ...funOptions.controllerMiddleware,
167
198
  ...funOptions.middleware,
168
199
  async (ctx, next) => {
200
+ let args;
169
201
  if (isHttpFunction) {
170
202
  args = [ctx];
171
203
  }
204
+ else {
205
+ args = [options.originEvent, options.originContext];
206
+ }
172
207
  // invoke handler
173
208
  const result = await this.invokeHandler(funOptions, ctx, args, isHttpFunction);
174
209
  if (isHttpFunction && result !== undefined) {
@@ -179,11 +214,8 @@ let MidwayFaaSFramework = class MidwayFaaSFramework extends core_1.BaseFramework
179
214
  ], this.app);
180
215
  return await fn(ctx, next);
181
216
  }))(context);
182
- if (isLegacyMode) {
183
- return result;
184
- }
185
- else if (isHttpFunction) {
186
- if (!context.response._explicitStatus) {
217
+ if (isHttpFunction) {
218
+ if (!((_a = context.response) === null || _a === void 0 ? void 0 : _a._explicitStatus)) {
187
219
  if (context.body === null || context.body === 'undefined') {
188
220
  context.body = '';
189
221
  context.type = 'text';
@@ -232,6 +264,11 @@ let MidwayFaaSFramework = class MidwayFaaSFramework extends core_1.BaseFramework
232
264
  }
233
265
  };
234
266
  }
267
+ async wrapHttpRequest(req, res) {
268
+ const newReq = res ? new serverless_http_parser_1.HTTPRequest(req, res) : req;
269
+ const newRes = new serverless_http_parser_1.HTTPResponse();
270
+ return this.createHttpContext(newReq, newRes);
271
+ }
235
272
  /**
236
273
  * @deprecated
237
274
  * @param middlewareId
@@ -325,6 +362,9 @@ let MidwayFaaSFramework = class MidwayFaaSFramework extends core_1.BaseFramework
325
362
  getEventMiddleware() {
326
363
  return this.eventMiddlewareManager;
327
364
  }
365
+ getAllHandlerNames() {
366
+ return Array.from(this.funMappingStore.keys());
367
+ }
328
368
  };
329
369
  __decorate([
330
370
  (0, decorator_1.Inject)(),
@@ -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
  }
@@ -44,8 +51,6 @@ export interface IFaaSConfigurationOptions extends IConfigurationOptions {
44
51
  getFunctionName(): string;
45
52
  getFunctionServiceName(): string;
46
53
  runAppHook?(app: Application): void;
47
- runEventHook?(...args: any[]): any | void;
48
- runRequestHook?(...args: any[]): any | void;
49
54
  };
50
55
  }
51
56
  /**
@@ -54,4 +59,16 @@ export interface IFaaSConfigurationOptions extends IConfigurationOptions {
54
59
  export interface IWebMiddleware {
55
60
  resolve(): FaaSMiddleware;
56
61
  }
62
+ export interface ServerlessStarterOptions extends IMidwayBootstrapOptions {
63
+ initializeMethodName?: string;
64
+ createAdapter?: () => Promise<{
65
+ close(): any;
66
+ createAppHook(app?: any): any;
67
+ }>;
68
+ performance?: {
69
+ mark(label: string): any;
70
+ end(): any;
71
+ };
72
+ exportAllHandler?: boolean;
73
+ }
57
74
  //# sourceMappingURL=interface.d.ts.map
package/package.json CHANGED
@@ -1,19 +1,19 @@
1
1
  {
2
2
  "name": "@midwayjs/faas",
3
- "version": "3.3.6-beta.5",
3
+ "version": "3.4.0-beta.1",
4
4
  "main": "dist/index",
5
5
  "typings": "index.d.ts",
6
6
  "dependencies": {
7
- "@midwayjs/core": "^3.3.5",
7
+ "@midwayjs/core": "^3.4.0-beta.1",
8
8
  "@midwayjs/faas-typings": "^3.3.5",
9
9
  "@midwayjs/logger": "^2.15.0",
10
- "@midwayjs/simple-lock": "^1.1.4",
11
- "@midwayjs/serverless-http-parser": "^3.3.5"
10
+ "@midwayjs/serverless-http-parser": "^3.3.5",
11
+ "@midwayjs/simple-lock": "^1.1.4"
12
12
  },
13
13
  "devDependencies": {
14
- "@midwayjs/decorator": "^3.3.4",
15
- "@midwayjs/mock": "^3.3.5",
16
- "@midwayjs/serverless-fc-starter": "^3.3.5",
14
+ "@midwayjs/decorator": "^3.4.0-beta.1",
15
+ "@midwayjs/mock": "^3.4.0-beta.1",
16
+ "@midwayjs/serverless-fc-starter": "^3.4.0-beta.1",
17
17
  "@midwayjs/serverless-scf-starter": "^3.3.5",
18
18
  "mm": "3.2.0"
19
19
  },