@midwayjs/core 3.3.6 → 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 +21 -0
- package/dist/baseFramework.d.ts +3 -0
- package/dist/baseFramework.js +32 -13
- package/dist/common/asyncContextManager.d.ts +61 -0
- package/dist/common/asyncContextManager.js +63 -0
- package/dist/common/dataSourceManager.d.ts +8 -1
- package/dist/common/dataSourceManager.js +61 -3
- package/dist/common/fileDetector.d.ts +1 -0
- package/dist/common/fileDetector.js +20 -0
- package/dist/common/filterManager.d.ts +1 -0
- package/dist/common/filterManager.js +37 -5
- package/dist/common/serviceFactory.js +2 -1
- package/dist/common/webGenerator.d.ts +4 -3
- package/dist/common/webGenerator.js +24 -15
- package/dist/config/config.default.d.ts +3 -0
- package/dist/config/config.default.js +3 -0
- package/dist/context/container.js +3 -0
- package/dist/error/base.d.ts +1 -1
- package/dist/error/base.js +6 -1
- package/dist/error/framework.d.ts +8 -0
- package/dist/error/framework.js +15 -1
- package/dist/error/http.js +16 -16
- package/dist/index.d.ts +5 -3
- package/dist/index.js +11 -3
- package/dist/interface.d.ts +14 -4
- package/dist/interface.js +3 -1
- package/dist/service/configService.js +7 -4
- package/dist/service/middlewareService.js +13 -5
- package/dist/service/slsFunctionService.d.ts +25 -0
- package/dist/service/slsFunctionService.js +242 -0
- package/dist/{common/webRouterCollector.d.ts → service/webRouterService.d.ts} +87 -36
- package/dist/{common/webRouterCollector.js → service/webRouterService.js} +121 -116
- package/dist/setup.js +3 -0
- package/dist/util/contextUtil.d.ts +2 -0
- package/dist/util/contextUtil.js +6 -1
- package/dist/util/index.d.ts +1 -0
- package/dist/util/index.js +23 -2
- package/dist/util/pathToRegexp.d.ts +113 -7
- package/dist/util/pathToRegexp.js +326 -205
- package/package.json +3 -3
- package/CHANGELOG.md +0 -2551
- package/dist/common/triggerCollector.d.ts +0 -8
- package/dist/common/triggerCollector.js +0 -37
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.
|
package/dist/baseFramework.d.ts
CHANGED
|
@@ -8,6 +8,7 @@ import { ContextMiddlewareManager } from './common/middlewareManager';
|
|
|
8
8
|
import { MidwayMiddlewareService } from './service/middlewareService';
|
|
9
9
|
import { FilterManager } from './common/filterManager';
|
|
10
10
|
import { MidwayMockService } from './service/mockService';
|
|
11
|
+
import { AsyncContextManager } from './common/asyncContextManager';
|
|
11
12
|
export declare abstract class BaseFramework<APP extends IMidwayApplication<CTX>, CTX extends IMidwayContext, OPT extends IConfigurationOptions, ResOrNext = unknown, Next = unknown> implements IMidwayFramework<APP, CTX, OPT, ResOrNext, Next> {
|
|
12
13
|
readonly applicationContext: IMidwayContainer;
|
|
13
14
|
app: APP;
|
|
@@ -20,6 +21,8 @@ export declare abstract class BaseFramework<APP extends IMidwayApplication<CTX>,
|
|
|
20
21
|
protected middlewareManager: ContextMiddlewareManager<CTX, ResOrNext, Next>;
|
|
21
22
|
protected filterManager: FilterManager<CTX, ResOrNext, Next>;
|
|
22
23
|
protected composeMiddleware: any;
|
|
24
|
+
protected bootstrapOptions: IMidwayBootstrapOptions;
|
|
25
|
+
protected asyncContextManager: AsyncContextManager;
|
|
23
26
|
loggerService: MidwayLoggerService;
|
|
24
27
|
environmentService: MidwayEnvironmentService;
|
|
25
28
|
configService: MidwayConfigService;
|
package/dist/baseFramework.js
CHANGED
|
@@ -22,6 +22,7 @@ const middlewareService_1 = require("./service/middlewareService");
|
|
|
22
22
|
const filterManager_1 = require("./common/filterManager");
|
|
23
23
|
const mockService_1 = require("./service/mockService");
|
|
24
24
|
const util = require("util");
|
|
25
|
+
const asyncContextManager_1 = require("./common/asyncContextManager");
|
|
25
26
|
const debug = util.debuglog('midway:debug');
|
|
26
27
|
class BaseFramework {
|
|
27
28
|
constructor(applicationContext) {
|
|
@@ -45,6 +46,7 @@ class BaseFramework {
|
|
|
45
46
|
return true;
|
|
46
47
|
}
|
|
47
48
|
async initialize(options) {
|
|
49
|
+
this.bootstrapOptions = options;
|
|
48
50
|
await this.beforeContainerInitialize(options);
|
|
49
51
|
await this.containerInitialize(options);
|
|
50
52
|
await this.afterContainerInitialize(options);
|
|
@@ -231,21 +233,38 @@ class BaseFramework {
|
|
|
231
233
|
*/
|
|
232
234
|
async afterContainerReady(options) { }
|
|
233
235
|
async applyMiddleware(lastMiddleware) {
|
|
236
|
+
var _a;
|
|
237
|
+
if (!this.applicationContext.hasObject(interface_1.ASYNC_CONTEXT_MANAGER_KEY)) {
|
|
238
|
+
const asyncContextManagerEnabled = this.configService.getConfiguration('asyncContextManager.enable') ||
|
|
239
|
+
false;
|
|
240
|
+
const contextManager = asyncContextManagerEnabled
|
|
241
|
+
? ((_a = this.bootstrapOptions) === null || _a === void 0 ? void 0 : _a.asyncContextManager) || new asyncContextManager_1.NoopContextManager()
|
|
242
|
+
: new asyncContextManager_1.NoopContextManager();
|
|
243
|
+
if (asyncContextManagerEnabled) {
|
|
244
|
+
contextManager.enable();
|
|
245
|
+
}
|
|
246
|
+
this.applicationContext.registerObject(interface_1.ASYNC_CONTEXT_MANAGER_KEY, contextManager);
|
|
247
|
+
}
|
|
234
248
|
if (!this.composeMiddleware) {
|
|
235
249
|
this.middlewareManager.insertFirst((async (ctx, next) => {
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
250
|
+
// warp with context manager
|
|
251
|
+
const rootContext = asyncContextManager_1.ASYNC_ROOT_CONTEXT.setValue(interface_1.ASYNC_CONTEXT_KEY, ctx);
|
|
252
|
+
const contextManager = this.applicationContext.get(interface_1.ASYNC_CONTEXT_MANAGER_KEY);
|
|
253
|
+
return await contextManager.with(rootContext, async () => {
|
|
254
|
+
this.mockService.applyContextMocks(this.app, ctx);
|
|
255
|
+
let returnResult = undefined;
|
|
256
|
+
try {
|
|
257
|
+
const result = await next();
|
|
258
|
+
returnResult = await this.filterManager.runResultFilter(result, ctx);
|
|
259
|
+
}
|
|
260
|
+
catch (err) {
|
|
261
|
+
returnResult = await this.filterManager.runErrorFilter(err, ctx);
|
|
262
|
+
}
|
|
263
|
+
if (returnResult.error) {
|
|
264
|
+
throw returnResult.error;
|
|
265
|
+
}
|
|
266
|
+
return returnResult.result;
|
|
267
|
+
});
|
|
249
268
|
}));
|
|
250
269
|
debug(`[core]: Compose middleware = [${this.middlewareManager.getNames()}]`);
|
|
251
270
|
this.composeMiddleware = await this.middlewareService.compose(this.middlewareManager, this.app);
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
export interface AsyncContext {
|
|
2
|
+
/**
|
|
3
|
+
* Get a value from the context.
|
|
4
|
+
*
|
|
5
|
+
* @param key key which identifies a context value
|
|
6
|
+
*/
|
|
7
|
+
getValue(key: symbol): unknown;
|
|
8
|
+
/**
|
|
9
|
+
* Create a new context which inherits from this context and has
|
|
10
|
+
* the given key set to the given value.
|
|
11
|
+
*
|
|
12
|
+
* @param key context key for which to set the value
|
|
13
|
+
* @param value value to set for the given key
|
|
14
|
+
*/
|
|
15
|
+
setValue(key: symbol, value: unknown): AsyncContext;
|
|
16
|
+
/**
|
|
17
|
+
* Return a new context which inherits from this context but does
|
|
18
|
+
* not contain a value for the given key.
|
|
19
|
+
*
|
|
20
|
+
* @param key context key for which to clear a value
|
|
21
|
+
*/
|
|
22
|
+
deleteValue(key: symbol): AsyncContext;
|
|
23
|
+
}
|
|
24
|
+
export interface AsyncContextManager {
|
|
25
|
+
/**
|
|
26
|
+
* Get the current active context
|
|
27
|
+
*/
|
|
28
|
+
active(): AsyncContext;
|
|
29
|
+
/**
|
|
30
|
+
* Run the fn callback with object set as the current active context
|
|
31
|
+
* @param context Any object to set as the current active context
|
|
32
|
+
* @param fn A callback to be immediately run within a specific context
|
|
33
|
+
* @param thisArg optional receiver to be used for calling fn
|
|
34
|
+
* @param args optional arguments forwarded to fn
|
|
35
|
+
*/
|
|
36
|
+
with<A extends unknown[], F extends (...args: A) => ReturnType<F>>(context: AsyncContext, fn: F, thisArg?: ThisParameterType<F>, ...args: A): ReturnType<F>;
|
|
37
|
+
/**
|
|
38
|
+
* Bind an object as the current context (or a specific one)
|
|
39
|
+
* @param [context] Optionally specify the context which you want to assign
|
|
40
|
+
* @param target Any object to which a context need to be set
|
|
41
|
+
*/
|
|
42
|
+
bind<T>(context: AsyncContext, target: T): T;
|
|
43
|
+
/**
|
|
44
|
+
* Enable context management
|
|
45
|
+
*/
|
|
46
|
+
enable(): this;
|
|
47
|
+
/**
|
|
48
|
+
* Disable context management
|
|
49
|
+
*/
|
|
50
|
+
disable(): this;
|
|
51
|
+
}
|
|
52
|
+
/** The root context is used as the default parent context when there is no active context */
|
|
53
|
+
export declare const ASYNC_ROOT_CONTEXT: AsyncContext;
|
|
54
|
+
export declare class NoopContextManager implements AsyncContextManager {
|
|
55
|
+
active(): AsyncContext;
|
|
56
|
+
with<A extends unknown[], F extends (...args: A) => ReturnType<F>>(_context: AsyncContext, fn: F, thisArg?: ThisParameterType<F>, ...args: A): ReturnType<F>;
|
|
57
|
+
bind<T>(_context: AsyncContext, target: T): T;
|
|
58
|
+
enable(): this;
|
|
59
|
+
disable(): this;
|
|
60
|
+
}
|
|
61
|
+
//# sourceMappingURL=asyncContextManager.d.ts.map
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/*
|
|
3
|
+
* Copyright The OpenTelemetry Authors
|
|
4
|
+
*
|
|
5
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
6
|
+
* you may not use this file except in compliance with the License.
|
|
7
|
+
* You may obtain a copy of the License at
|
|
8
|
+
*
|
|
9
|
+
* https://www.apache.org/licenses/LICENSE-2.0
|
|
10
|
+
*
|
|
11
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
12
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
13
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
14
|
+
* See the License for the specific language governing permissions and
|
|
15
|
+
* limitations under the License.
|
|
16
|
+
*/
|
|
17
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
18
|
+
exports.NoopContextManager = exports.ASYNC_ROOT_CONTEXT = void 0;
|
|
19
|
+
class AsyncBaseContext {
|
|
20
|
+
/**
|
|
21
|
+
* Construct a new context which inherits values from an optional parent context.
|
|
22
|
+
*
|
|
23
|
+
* @param parentContext a context from which to inherit values
|
|
24
|
+
*/
|
|
25
|
+
constructor(parentContext) {
|
|
26
|
+
// for minification
|
|
27
|
+
// eslint-disable-next-line @typescript-eslint/no-this-alias
|
|
28
|
+
const self = this;
|
|
29
|
+
self._currentContext = parentContext ? new Map(parentContext) : new Map();
|
|
30
|
+
self.getValue = (key) => self._currentContext.get(key);
|
|
31
|
+
self.setValue = (key, value) => {
|
|
32
|
+
const context = new AsyncBaseContext(self._currentContext);
|
|
33
|
+
context._currentContext.set(key, value);
|
|
34
|
+
return context;
|
|
35
|
+
};
|
|
36
|
+
self.deleteValue = (key) => {
|
|
37
|
+
const context = new AsyncBaseContext(self._currentContext);
|
|
38
|
+
context._currentContext.delete(key);
|
|
39
|
+
return context;
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
/** The root context is used as the default parent context when there is no active context */
|
|
44
|
+
exports.ASYNC_ROOT_CONTEXT = new AsyncBaseContext();
|
|
45
|
+
class NoopContextManager {
|
|
46
|
+
active() {
|
|
47
|
+
return exports.ASYNC_ROOT_CONTEXT;
|
|
48
|
+
}
|
|
49
|
+
with(_context, fn, thisArg, ...args) {
|
|
50
|
+
return fn.call(thisArg, ...args);
|
|
51
|
+
}
|
|
52
|
+
bind(_context, target) {
|
|
53
|
+
return target;
|
|
54
|
+
}
|
|
55
|
+
enable() {
|
|
56
|
+
return this;
|
|
57
|
+
}
|
|
58
|
+
disable() {
|
|
59
|
+
return this;
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
exports.NoopContextManager = NoopContextManager;
|
|
63
|
+
//# sourceMappingURL=asyncContextManager.js.map
|
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
export declare abstract class DataSourceManager<T> {
|
|
2
2
|
protected dataSource: Map<string, T>;
|
|
3
3
|
protected options: {};
|
|
4
|
-
protected
|
|
4
|
+
protected modelMapping: WeakMap<object, any>;
|
|
5
|
+
protected initDataSource(options: any, appDir: string): Promise<void>;
|
|
5
6
|
/**
|
|
6
7
|
* get a data source instance
|
|
7
8
|
* @param dataSourceName
|
|
@@ -19,10 +20,16 @@ export declare abstract class DataSourceManager<T> {
|
|
|
19
20
|
*/
|
|
20
21
|
isConnected(dataSourceName: string): Promise<boolean>;
|
|
21
22
|
createInstance(config: any, clientName: any): Promise<T | void>;
|
|
23
|
+
/**
|
|
24
|
+
* get data source name by model or repository
|
|
25
|
+
* @param modelOrRepository
|
|
26
|
+
*/
|
|
27
|
+
getDataSourceNameByModel(modelOrRepository: any): string | undefined;
|
|
22
28
|
abstract getName(): string;
|
|
23
29
|
protected abstract createDataSource(config: any, dataSourceName: string): Promise<T | void> | (T | void);
|
|
24
30
|
protected abstract checkConnected(dataSource: T): Promise<boolean>;
|
|
25
31
|
protected destroyDataSource(dataSource: T): Promise<void>;
|
|
26
32
|
stop(): Promise<void>;
|
|
27
33
|
}
|
|
34
|
+
export declare function globModels(globString: string, appDir: string): any[];
|
|
28
35
|
//# sourceMappingURL=dataSourceManager.d.ts.map
|
|
@@ -1,22 +1,48 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.DataSourceManager = void 0;
|
|
3
|
+
exports.globModels = exports.DataSourceManager = void 0;
|
|
4
4
|
/**
|
|
5
5
|
* 数据源管理器实现
|
|
6
6
|
*/
|
|
7
7
|
const extend_1 = require("../util/extend");
|
|
8
8
|
const error_1 = require("../error");
|
|
9
|
+
const glob_1 = require("@midwayjs/glob");
|
|
10
|
+
const path_1 = require("path");
|
|
11
|
+
const decorator_1 = require("@midwayjs/decorator");
|
|
12
|
+
const DEFAULT_PATTERN = ['**/**.ts', '**/**.js'];
|
|
9
13
|
class DataSourceManager {
|
|
10
14
|
constructor() {
|
|
11
15
|
this.dataSource = new Map();
|
|
12
16
|
this.options = {};
|
|
17
|
+
this.modelMapping = new WeakMap();
|
|
13
18
|
}
|
|
14
|
-
async initDataSource(options
|
|
19
|
+
async initDataSource(options, appDir) {
|
|
15
20
|
this.options = options;
|
|
16
21
|
if (options.dataSource) {
|
|
17
22
|
for (const dataSourceName in options.dataSource) {
|
|
23
|
+
const dataSourceOptions = options.dataSource[dataSourceName];
|
|
24
|
+
if (dataSourceOptions['entities']) {
|
|
25
|
+
const entities = new Set();
|
|
26
|
+
// loop entities and glob files to model
|
|
27
|
+
for (const entity of dataSourceOptions['entities']) {
|
|
28
|
+
if (typeof entity === 'string') {
|
|
29
|
+
// string will be glob file
|
|
30
|
+
const models = globModels(entity, appDir);
|
|
31
|
+
for (const model of models) {
|
|
32
|
+
entities.add(model);
|
|
33
|
+
this.modelMapping.set(model, dataSourceName);
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
else {
|
|
37
|
+
// model will be add to array
|
|
38
|
+
entities.add(entity);
|
|
39
|
+
this.modelMapping.set(entity, dataSourceName);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
dataSourceOptions['entities'] = Array.from(entities);
|
|
43
|
+
}
|
|
18
44
|
// create data source
|
|
19
|
-
await this.createInstance(
|
|
45
|
+
await this.createInstance(dataSourceOptions, dataSourceName);
|
|
20
46
|
}
|
|
21
47
|
}
|
|
22
48
|
else {
|
|
@@ -58,12 +84,44 @@ class DataSourceManager {
|
|
|
58
84
|
return client;
|
|
59
85
|
}
|
|
60
86
|
}
|
|
87
|
+
/**
|
|
88
|
+
* get data source name by model or repository
|
|
89
|
+
* @param modelOrRepository
|
|
90
|
+
*/
|
|
91
|
+
getDataSourceNameByModel(modelOrRepository) {
|
|
92
|
+
return this.modelMapping.get(modelOrRepository);
|
|
93
|
+
}
|
|
61
94
|
async destroyDataSource(dataSource) { }
|
|
62
95
|
async stop() {
|
|
63
96
|
for (const value of this.dataSource.values()) {
|
|
64
97
|
await this.destroyDataSource(value);
|
|
65
98
|
}
|
|
99
|
+
this.dataSource.clear();
|
|
66
100
|
}
|
|
67
101
|
}
|
|
68
102
|
exports.DataSourceManager = DataSourceManager;
|
|
103
|
+
function globModels(globString, appDir) {
|
|
104
|
+
const cwd = (0, path_1.join)(appDir, globString);
|
|
105
|
+
const models = [];
|
|
106
|
+
// string will be glob file
|
|
107
|
+
const files = (0, glob_1.run)(DEFAULT_PATTERN, {
|
|
108
|
+
cwd,
|
|
109
|
+
});
|
|
110
|
+
for (const file of files) {
|
|
111
|
+
const exports = require(file);
|
|
112
|
+
if (decorator_1.Types.isClass(exports)) {
|
|
113
|
+
models.push(exports);
|
|
114
|
+
}
|
|
115
|
+
else {
|
|
116
|
+
for (const m in exports) {
|
|
117
|
+
const module = exports[m];
|
|
118
|
+
if (decorator_1.Types.isClass(module)) {
|
|
119
|
+
models.push(module);
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
return models;
|
|
125
|
+
}
|
|
126
|
+
exports.globModels = globModels;
|
|
69
127
|
//# sourceMappingURL=dataSourceManager.js.map
|
|
@@ -13,6 +13,7 @@ export declare class DirectoryFileDetector extends AbstractFileDetector<{
|
|
|
13
13
|
namespace: string;
|
|
14
14
|
}> {
|
|
15
15
|
private directoryFilterArray;
|
|
16
|
+
private duplicateModuleCheckSet;
|
|
16
17
|
run(container: any): void;
|
|
17
18
|
}
|
|
18
19
|
export declare class CustomModuleDetector extends AbstractFileDetector<{
|
|
@@ -3,6 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|
|
3
3
|
exports.CustomModuleDetector = exports.DirectoryFileDetector = exports.AbstractFileDetector = void 0;
|
|
4
4
|
const decorator_1 = require("@midwayjs/decorator");
|
|
5
5
|
const glob_1 = require("@midwayjs/glob");
|
|
6
|
+
const error_1 = require("../error");
|
|
6
7
|
class AbstractFileDetector {
|
|
7
8
|
constructor(options) {
|
|
8
9
|
this.options = options;
|
|
@@ -31,6 +32,7 @@ class DirectoryFileDetector extends AbstractFileDetector {
|
|
|
31
32
|
constructor() {
|
|
32
33
|
super(...arguments);
|
|
33
34
|
this.directoryFilterArray = [];
|
|
35
|
+
this.duplicateModuleCheckSet = new Map();
|
|
34
36
|
}
|
|
35
37
|
run(container) {
|
|
36
38
|
const loadDirs = []
|
|
@@ -41,6 +43,20 @@ class DirectoryFileDetector extends AbstractFileDetector {
|
|
|
41
43
|
cwd: dir,
|
|
42
44
|
ignore: DEFAULT_IGNORE_PATTERN.concat(this.options.ignore || []).concat(this.extraDetectorOptions.ignore || []),
|
|
43
45
|
});
|
|
46
|
+
// 检查重复模块
|
|
47
|
+
const checkDuplicatedHandler = (module, options) => {
|
|
48
|
+
if (decorator_1.Types.isClass(module)) {
|
|
49
|
+
const name = (0, decorator_1.getProviderName)(module);
|
|
50
|
+
if (name) {
|
|
51
|
+
if (this.duplicateModuleCheckSet.has(name)) {
|
|
52
|
+
throw new error_1.MidwayDuplicateClassNameError(name, options.srcPath, this.duplicateModuleCheckSet.get(name));
|
|
53
|
+
}
|
|
54
|
+
else {
|
|
55
|
+
this.duplicateModuleCheckSet.set(name, options.srcPath);
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
};
|
|
44
60
|
for (const file of fileResults) {
|
|
45
61
|
if (this.directoryFilterArray.length) {
|
|
46
62
|
for (const resolveFilter of this.directoryFilterArray) {
|
|
@@ -68,6 +84,7 @@ class DirectoryFileDetector extends AbstractFileDetector {
|
|
|
68
84
|
namespace: this.options.namespace,
|
|
69
85
|
srcPath: file,
|
|
70
86
|
createFrom: 'file',
|
|
87
|
+
bindHook: checkDuplicatedHandler,
|
|
71
88
|
});
|
|
72
89
|
}
|
|
73
90
|
}
|
|
@@ -78,10 +95,13 @@ class DirectoryFileDetector extends AbstractFileDetector {
|
|
|
78
95
|
namespace: this.options.namespace,
|
|
79
96
|
srcPath: file,
|
|
80
97
|
createFrom: 'file',
|
|
98
|
+
bindHook: checkDuplicatedHandler,
|
|
81
99
|
});
|
|
82
100
|
}
|
|
83
101
|
}
|
|
84
102
|
}
|
|
103
|
+
// check end
|
|
104
|
+
this.duplicateModuleCheckSet.clear();
|
|
85
105
|
}
|
|
86
106
|
}
|
|
87
107
|
exports.DirectoryFileDetector = DirectoryFileDetector;
|
|
@@ -5,6 +5,7 @@ export declare class FilterManager<CTX extends IMidwayContext = IMidwayContext,
|
|
|
5
5
|
private exceptionMap;
|
|
6
6
|
private defaultErrFilter;
|
|
7
7
|
private matchFnList;
|
|
8
|
+
private protoMatchList;
|
|
8
9
|
useFilter(Filters: CommonFilterUnion<CTX, R, N>): void;
|
|
9
10
|
init(applicationContext: IMidwayContainer): Promise<void>;
|
|
10
11
|
runErrorFilter(err: Error, ctx: CTX, res?: R, next?: N): Promise<{
|
|
@@ -10,6 +10,7 @@ class FilterManager {
|
|
|
10
10
|
this.exceptionMap = new WeakMap();
|
|
11
11
|
this.defaultErrFilter = undefined;
|
|
12
12
|
this.matchFnList = [];
|
|
13
|
+
this.protoMatchList = [];
|
|
13
14
|
}
|
|
14
15
|
useFilter(Filters) {
|
|
15
16
|
if (!Array.isArray(Filters)) {
|
|
@@ -31,7 +32,20 @@ class FilterManager {
|
|
|
31
32
|
const exceptionMetadata = (0, decorator_1.getClassMetadata)(decorator_1.CATCH_KEY, FilterClass);
|
|
32
33
|
if (exceptionMetadata && exceptionMetadata.catchTargets) {
|
|
33
34
|
for (const Exception of exceptionMetadata.catchTargets) {
|
|
34
|
-
this.exceptionMap.set(Exception,
|
|
35
|
+
this.exceptionMap.set(Exception, {
|
|
36
|
+
filter,
|
|
37
|
+
catchOptions: exceptionMetadata.catchOptions || {},
|
|
38
|
+
});
|
|
39
|
+
if (exceptionMetadata.catchOptions['matchPrototype']) {
|
|
40
|
+
this.protoMatchList.push(err => {
|
|
41
|
+
if (err instanceof Exception) {
|
|
42
|
+
return Exception;
|
|
43
|
+
}
|
|
44
|
+
else {
|
|
45
|
+
return false;
|
|
46
|
+
}
|
|
47
|
+
});
|
|
48
|
+
}
|
|
35
49
|
}
|
|
36
50
|
}
|
|
37
51
|
else {
|
|
@@ -53,14 +67,32 @@ class FilterManager {
|
|
|
53
67
|
}
|
|
54
68
|
async runErrorFilter(err, ctx, res, next) {
|
|
55
69
|
let result, error;
|
|
70
|
+
let matched = false;
|
|
56
71
|
if (this.exceptionMap.has(err.constructor)) {
|
|
57
|
-
|
|
58
|
-
|
|
72
|
+
matched = true;
|
|
73
|
+
const filterData = this.exceptionMap.get(err.constructor);
|
|
74
|
+
result = await filterData.filter.catch(err, ctx, res, next);
|
|
59
75
|
}
|
|
60
|
-
|
|
76
|
+
// match with prototype
|
|
77
|
+
if (!matched && this.protoMatchList.length) {
|
|
78
|
+
let protoException;
|
|
79
|
+
for (const matchPattern of this.protoMatchList) {
|
|
80
|
+
protoException = matchPattern(err);
|
|
81
|
+
if (protoException) {
|
|
82
|
+
break;
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
if (protoException) {
|
|
86
|
+
matched = true;
|
|
87
|
+
const filterData = this.exceptionMap.get(protoException);
|
|
88
|
+
result = await filterData.filter.catch(err, ctx, res, next);
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
if (!matched && this.defaultErrFilter) {
|
|
92
|
+
matched = true;
|
|
61
93
|
result = await this.defaultErrFilter.catch(err, ctx, res, next);
|
|
62
94
|
}
|
|
63
|
-
|
|
95
|
+
if (!matched) {
|
|
64
96
|
error = err;
|
|
65
97
|
}
|
|
66
98
|
return {
|
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.ServiceFactory = void 0;
|
|
4
4
|
const assert = require("assert");
|
|
5
|
+
const extend_1 = require("../util/extend");
|
|
5
6
|
/**
|
|
6
7
|
* 多客户端工厂实现
|
|
7
8
|
*/
|
|
@@ -33,7 +34,7 @@ class ServiceFactory {
|
|
|
33
34
|
}
|
|
34
35
|
async createInstance(config, clientName) {
|
|
35
36
|
// options.default will be merge in to options.clients[id]
|
|
36
|
-
config =
|
|
37
|
+
config = (0, extend_1.extend)(true, {}, this.options['default'], config);
|
|
37
38
|
const client = await this.createClient(config, clientName);
|
|
38
39
|
if (client) {
|
|
39
40
|
if (clientName) {
|
|
@@ -1,15 +1,16 @@
|
|
|
1
|
-
import { RouterInfo, IMidwayApplication } from '../index';
|
|
1
|
+
import { MidwayWebRouterService, RouterInfo, IMidwayApplication } from '../index';
|
|
2
2
|
export declare abstract class WebControllerGenerator<Router extends {
|
|
3
3
|
use: (...args: any[]) => void;
|
|
4
4
|
}> {
|
|
5
5
|
readonly app: IMidwayApplication;
|
|
6
|
-
|
|
6
|
+
readonly midwayWebRouterService: MidwayWebRouterService;
|
|
7
|
+
protected constructor(app: IMidwayApplication, midwayWebRouterService: MidwayWebRouterService);
|
|
7
8
|
/**
|
|
8
9
|
* wrap controller string to middleware function
|
|
9
10
|
* @param routeInfo
|
|
10
11
|
*/
|
|
11
12
|
generateKoaController(routeInfo: RouterInfo): (ctx: any, next: any) => Promise<void>;
|
|
12
|
-
loadMidwayController(
|
|
13
|
+
loadMidwayController(routerHandler?: (newRouter: Router) => void): Promise<void>;
|
|
13
14
|
abstract createRouter(routerOptions: any): Router;
|
|
14
15
|
abstract generateController(routeInfo: RouterInfo): any;
|
|
15
16
|
}
|
|
@@ -12,8 +12,9 @@ const index_1 = require("../index");
|
|
|
12
12
|
const util = require("util");
|
|
13
13
|
const debug = util.debuglog('midway:debug');
|
|
14
14
|
class WebControllerGenerator {
|
|
15
|
-
constructor(app) {
|
|
15
|
+
constructor(app, midwayWebRouterService) {
|
|
16
16
|
this.app = app;
|
|
17
|
+
this.midwayWebRouterService = midwayWebRouterService;
|
|
17
18
|
}
|
|
18
19
|
/**
|
|
19
20
|
* wrap controller string to middleware function
|
|
@@ -22,14 +23,24 @@ class WebControllerGenerator {
|
|
|
22
23
|
generateKoaController(routeInfo) {
|
|
23
24
|
return async (ctx, next) => {
|
|
24
25
|
const args = [ctx, next];
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
26
|
+
let result;
|
|
27
|
+
if (typeof routeInfo.method !== 'string') {
|
|
28
|
+
result = await routeInfo.method(ctx, next);
|
|
29
|
+
}
|
|
30
|
+
else {
|
|
31
|
+
const controller = await ctx.requestContext.getAsync(routeInfo.id);
|
|
32
|
+
// eslint-disable-next-line prefer-spread
|
|
33
|
+
result = await controller[routeInfo.method].apply(controller, args);
|
|
30
34
|
}
|
|
31
|
-
if (
|
|
32
|
-
|
|
35
|
+
if (result !== undefined) {
|
|
36
|
+
if (result === null) {
|
|
37
|
+
// 这样设置可以绕过 koa 的 _explicitStatus 赋值机制
|
|
38
|
+
ctx.response._body = null;
|
|
39
|
+
ctx.response._midwayControllerNullBody = true;
|
|
40
|
+
}
|
|
41
|
+
else {
|
|
42
|
+
ctx.body = result;
|
|
43
|
+
}
|
|
33
44
|
}
|
|
34
45
|
// implement response decorator
|
|
35
46
|
if (Array.isArray(routeInfo.responseMetadata) &&
|
|
@@ -56,13 +67,10 @@ class WebControllerGenerator {
|
|
|
56
67
|
}
|
|
57
68
|
};
|
|
58
69
|
}
|
|
59
|
-
async loadMidwayController(
|
|
70
|
+
async loadMidwayController(routerHandler) {
|
|
60
71
|
var _a, _b;
|
|
61
|
-
const
|
|
62
|
-
|
|
63
|
-
});
|
|
64
|
-
const routerTable = await collector.getRouterTable();
|
|
65
|
-
const routerList = await collector.getRoutePriorityList();
|
|
72
|
+
const routerTable = await this.midwayWebRouterService.getRouterTable();
|
|
73
|
+
const routerList = await this.midwayWebRouterService.getRoutePriorityList();
|
|
66
74
|
const applicationContext = this.app.getApplicationContext();
|
|
67
75
|
const logger = this.app.getCoreLogger();
|
|
68
76
|
const middlewareService = applicationContext.get(index_1.MidwayMiddlewareService);
|
|
@@ -93,6 +101,7 @@ class WebControllerGenerator {
|
|
|
93
101
|
methodMiddlewares.push(routeMiddlewareFn);
|
|
94
102
|
}
|
|
95
103
|
if (this.app.getFrameworkType() === decorator_1.MidwayFrameworkType.WEB_KOA) {
|
|
104
|
+
// egg use path-to-regexp v1 but koa use v6
|
|
96
105
|
if (typeof routeInfo.url === 'string' && /\*$/.test(routeInfo.url)) {
|
|
97
106
|
routeInfo.url = routeInfo.url.replace('*', '(.*)');
|
|
98
107
|
}
|
|
@@ -107,7 +116,7 @@ class WebControllerGenerator {
|
|
|
107
116
|
debug(`[core]: Load Router "${routeInfo.requestMethod.toUpperCase()} ${routeInfo.url}"`);
|
|
108
117
|
// apply controller from request context
|
|
109
118
|
// eslint-disable-next-line prefer-spread
|
|
110
|
-
newRouter[routeInfo.requestMethod].apply(newRouter, routerArgs);
|
|
119
|
+
newRouter[routeInfo.requestMethod.toLowerCase()].apply(newRouter, routerArgs);
|
|
111
120
|
}
|
|
112
121
|
routerHandler && routerHandler(newRouter);
|
|
113
122
|
}
|
|
@@ -8,6 +8,9 @@ exports.default = (appInfo) => {
|
|
|
8
8
|
const isDevelopment = (0, util_1.isDevelopmentEnvironment)((0, util_1.getCurrentEnvironment)());
|
|
9
9
|
const logRoot = (_a = process.env[interface_1.MIDWAY_LOGGER_WRITEABLE_DIR]) !== null && _a !== void 0 ? _a : appInfo.root;
|
|
10
10
|
return {
|
|
11
|
+
asyncContextManager: {
|
|
12
|
+
enable: false,
|
|
13
|
+
},
|
|
11
14
|
midwayLogger: {
|
|
12
15
|
default: {
|
|
13
16
|
dir: (0, path_1.join)(logRoot, 'logs', appInfo.name),
|
|
@@ -274,6 +274,9 @@ class MidwayContainer {
|
|
|
274
274
|
// 如果 definition 存在就不再重复 bind
|
|
275
275
|
return;
|
|
276
276
|
}
|
|
277
|
+
if (options === null || options === void 0 ? void 0 : options.bindHook) {
|
|
278
|
+
options.bindHook(target, options);
|
|
279
|
+
}
|
|
277
280
|
let definition;
|
|
278
281
|
if (decorator_1.Types.isClass(target)) {
|
|
279
282
|
definition = new objectDefinition_1.ObjectDefinition();
|
package/dist/error/base.d.ts
CHANGED
|
@@ -22,7 +22,7 @@ export declare class MidwayError extends Error {
|
|
|
22
22
|
}
|
|
23
23
|
export declare type ResOrMessage = string | {
|
|
24
24
|
message: string;
|
|
25
|
-
};
|
|
25
|
+
} | undefined;
|
|
26
26
|
export declare class MidwayHttpError extends MidwayError {
|
|
27
27
|
status: number;
|
|
28
28
|
constructor(resOrMessage: ResOrMessage, status: number);
|