Skip to content

Commit

Permalink
feat: add aop (#640)
Browse files Browse the repository at this point in the history
  • Loading branch information
czy88840616 committed Sep 18, 2020
1 parent 26ee626 commit c3e15b3
Show file tree
Hide file tree
Showing 78 changed files with 1,211 additions and 489 deletions.
2 changes: 1 addition & 1 deletion package.json
Expand Up @@ -27,7 +27,7 @@
"next": "sh scripts/publish.sh --npm-tag next",
"release": "rm -f ./packages/.DS* && sh scripts/publish.sh",
"bootstrap": "rm -f ./packages/.DS* && lerna bootstrap",
"clean": "lerna clean --yes && rm -rf ./packages/**/package-lock.json",
"clean": "lerna clean --yes && rm -rf ./packages/**/package-lock.json && rm -f package-lock.json",
"build": "sh scripts/build.sh",
"authors": "git log --format='%aN <%aE>' | sort -u > AUTHORS",
"postinstall": "opencollective-postinstall",
Expand Down
18 changes: 5 additions & 13 deletions packages/bootstrap/src/bootstrap.ts
Expand Up @@ -26,7 +26,7 @@ export class BootstrapStarter {
}

public async init() {
this.appDir = this.globalOptions.baseDir;
this.appDir = this.globalOptions.baseDir;
await Promise.all(
this.getActions('initialize', {
...this.globalOptions,
Expand All @@ -37,15 +37,11 @@ export class BootstrapStarter {
}

public async run() {
await Promise.all(
this.getActions('run', {})
);
await Promise.all(this.getActions('run', {}));
}

public async stop() {
await Promise.all(
this.getActions('stop', {})
);
await Promise.all(this.getActions('stop', {}));
}

public getActions(action: string, args?): any[] {
Expand Down Expand Up @@ -93,14 +89,10 @@ export class Bootstrap {

static async run() {
await this.getStarter().init();
return this.getStarter().run().catch(
console.error
);
return this.getStarter().run().catch(console.error);
}

static async stop() {
return this.getStarter().stop().catch(
console.error
);
return this.getStarter().stop().catch(console.error);
}
}
6 changes: 5 additions & 1 deletion packages/bootstrap/src/index.ts
@@ -1 +1,5 @@
export { isTypeScriptEnvironment, Bootstrap, BootstrapStarter } from './bootstrap';
export {
isTypeScriptEnvironment,
Bootstrap,
BootstrapStarter,
} from './bootstrap';
2 changes: 2 additions & 0 deletions packages/core/package.json
Expand Up @@ -30,6 +30,7 @@
"dependencies": {
"@midwayjs/decorator": "^2.2.5",
"@midwayjs/glob": "^1.0.2",
"class-transformer": "^0.3.1",
"debug": "^4.1.1",
"extend2": "^1.0.0",
"is-type-of": "^1.2.1",
Expand All @@ -39,6 +40,7 @@
"lodash.get": "^4.4.2",
"lodash.set": "^4.3.2",
"lodash.template": "^4.4.0",
"picomatch": "^2.2.2",
"reflect-metadata": "^0.1.13"
},
"author": "Harry Chen <czy88840616@gmail.com>",
Expand Down
15 changes: 6 additions & 9 deletions packages/core/src/baseFramework.ts
Expand Up @@ -3,7 +3,8 @@ import {
IMidwayApplication,
IMidwayBootstrapOptions,
IMidwayContainer,
IMidwayFramework, MidwayFrameworkType,
IMidwayFramework,
MidwayFrameworkType,
} from './interface';
import { ContainerLoader } from './';
import { APPLICATION_KEY, CONFIG_KEY } from '@midwayjs/decorator';
Expand Down Expand Up @@ -95,23 +96,19 @@ export abstract class BaseFramework<T extends IConfigurationOptions>
await this.containerLoader.stop();
}

protected async beforeStop(): Promise<void> {
}
protected async beforeStop(): Promise<void> {}

protected async beforeInitialize(
options: Partial<IMidwayBootstrapOptions>
): Promise<void> {
};
): Promise<void> {}

protected async beforeDirectoryLoad(
options: Partial<IMidwayBootstrapOptions>
): Promise<void> {
};
): Promise<void> {}

protected async afterDirectoryLoad(
options: Partial<IMidwayBootstrapOptions>
): Promise<void> {
};
): Promise<void> {}

protected abstract async afterInitialize(
options: Partial<IMidwayBootstrapOptions>
Expand Down
4 changes: 2 additions & 2 deletions packages/core/src/common/constants.ts
Expand Up @@ -41,7 +41,7 @@ export const KEYS = {
ASPECT_ELEMENT: 'aspect',
AROUND_ELEMENT: 'around',
EXPRESSION_ATTRIBUTE: 'expression',
EXECUTE_ATTRIBUTE: 'execute'
EXECUTE_ATTRIBUTE: 'execute',
};

export const VALUE_TYPE = {
Expand All @@ -52,5 +52,5 @@ export const VALUE_TYPE = {
TEMPLATE: 'template',
MANAGED: 'managed',
OBJECT: 'object', // 浠呬粎鍦ㄨВ鏋愭椂浣跨敤
BOOLEAN: 'boolean'
BOOLEAN: 'boolean',
};
11 changes: 1 addition & 10 deletions packages/core/src/common/lodashWrap.ts
@@ -1,4 +1,3 @@

import * as assign from 'lodash.assign';
import * as get from 'lodash.get';
import * as set from 'lodash.set';
Expand All @@ -8,12 +7,4 @@ import * as defaultsDeep from 'lodash.defaultsdeep';

const isArray = Array.isArray;

export {
assign,
set,
get,
isArray,
template,
cloneDeep,
defaultsDeep,
};
export { assign, set, get, isArray, template, cloneDeep, defaultsDeep };
4 changes: 3 additions & 1 deletion packages/core/src/common/notFoundError.ts
Expand Up @@ -10,7 +10,9 @@ export class NotFoundError extends Error {
this[NotFoundError.type] = NotFoundError.type;
}
updateErrorMsg(className: string): void {
const identifier = this.message.split(' is not valid in current context')[0];
const identifier = this.message.split(
' is not valid in current context'
)[0];
const msg = `${identifier} in class ${className} is not valid in current context`;
this.message = msg;
}
Expand Down
6 changes: 5 additions & 1 deletion packages/core/src/common/reflectTool.ts
Expand Up @@ -64,7 +64,11 @@ export function recursiveGetPrototypeOf(target: any): any[] {
* @param metadataKey metadata's key
* @param target the target of metadataKey
*/
export function recursiveGetMetadata(metadataKey: any, target: any, propertyKey?: string | symbol): ReflectResult[] {
export function recursiveGetMetadata(
metadataKey: any,
target: any,
propertyKey?: string | symbol
): ReflectResult[] {
const metadatas: ReflectResult[] = [];

// get metadata value of a metadata key on the prototype
Expand Down
1 change: 1 addition & 0 deletions packages/core/src/common/util.ts
Expand Up @@ -13,6 +13,7 @@ export const safeRequire = p => {
};

export const isPath = (p): boolean => {
// eslint-disable-next-line no-useless-escape
if (/(^[\.\/])|:|\\/.test(p)) {
return true;
}
Expand Down
74 changes: 51 additions & 23 deletions packages/core/src/context/applicationContext.ts
Expand Up @@ -8,7 +8,7 @@ import {
IObjectDefinition,
IObjectDefinitionRegistry,
IObjectFactory,
ObjectDependencyTree
ObjectDependencyTree,
} from '../interface';
import { ObjectProperties } from '../definitions/properties';
import { ManagedResolverFactory } from './managedResolverFactory';
Expand All @@ -17,7 +17,9 @@ import { parsePrefix, isPathEqual } from '../common/util';

const PREFIX = '_id_default_';

export class ObjectDefinitionRegistry extends Map implements IObjectDefinitionRegistry {
export class ObjectDefinitionRegistry
extends Map
implements IObjectDefinitionRegistry {
private singletonIds = [];

get identifiers() {
Expand Down Expand Up @@ -49,7 +51,10 @@ export class ObjectDefinitionRegistry extends Map implements IObjectDefinitionRe
return definitions;
}

registerDefinition(identifier: ObjectIdentifier, definition: IObjectDefinition) {
registerDefinition(
identifier: ObjectIdentifier,
definition: IObjectDefinition
) {
if (definition.isSingletonScope()) {
this.singletonIds.push(identifier);
}
Expand Down Expand Up @@ -96,7 +101,8 @@ export class ObjectDefinitionRegistry extends Map implements IObjectDefinitionRe
}
}

export class BaseApplicationContext implements IApplicationContext, IObjectFactory {
export class BaseApplicationContext
implements IApplicationContext, IObjectFactory {
protected readied = false;
private _resolverFactory: ManagedResolverFactory = null;
private _registry: IObjectDefinitionRegistry = null;
Expand Down Expand Up @@ -145,8 +151,7 @@ export class BaseApplicationContext implements IApplicationContext, IObjectFacto
/**
* 缁ф壙瀹炵幇鏃堕渶瑕佽皟鐢╯uper
*/
protected init(): void {
}
protected init(): void {}

async stop(): Promise<void> {
await this.getManagedResolverFactory().destroyCache();
Expand All @@ -159,8 +164,7 @@ export class BaseApplicationContext implements IApplicationContext, IObjectFacto
this.readied = true;
}

protected loadDefinitions(): void {
}
protected loadDefinitions(): void {}

isAsync(identifier: ObjectIdentifier): boolean {
if (this.registry.hasDefinition(identifier)) {
Expand Down Expand Up @@ -224,11 +228,16 @@ export class BaseApplicationContext implements IApplicationContext, IObjectFacto
* @param {ObjectIdentifier} identifier
* @param {IObjectDefinition} definition
*/
registerDefinition(identifier: ObjectIdentifier, definition: IObjectDefinition) {
registerDefinition(
identifier: ObjectIdentifier,
definition: IObjectDefinition
) {
if (!this.disableConflictCheck && this.registry.hasDefinition(identifier)) {
const def = this.registry.getDefinition(identifier);
if (!isPathEqual(definition.srcPath, def.srcPath)) {
throw new Error(`${identifier} path = ${definition.srcPath} is exist (${def.srcPath})!`);
throw new Error(
`${identifier} path = ${definition.srcPath} is exist (${def.srcPath})!`
);
}
}
this.registry.registerDefinition(identifier, definition);
Expand All @@ -248,34 +257,53 @@ export class BaseApplicationContext implements IApplicationContext, IObjectFacto
* register handler after instance create
* @param fn
*/
afterEachCreated(fn: (ins: any, context: IApplicationContext, definition?: IObjectDefinition) => void) {
afterEachCreated(
fn: (
ins: any,
context: IApplicationContext,
definition?: IObjectDefinition
) => void
) {
this.getManagedResolverFactory().afterEachCreated(fn);
}

/**
* register handler before instance create
* @param fn
*/
beforeEachCreated(fn: (Clzz: any, constructorArgs: any[], context: IApplicationContext) => void) {
beforeEachCreated(
fn: (
Clzz: any,
constructorArgs: any[],
context: IApplicationContext
) => void
) {
this.getManagedResolverFactory().beforeEachCreated(fn);
}

protected createObjectDependencyTree(identifier, definition) {
if (!this.dependencyMap.has(identifier)) {

let constructorArgs = definition.constructorArgs || [];
constructorArgs = constructorArgs.map((ref) => {
return ref.name;
}).filter(name => {
return !!name;
});

const properties = (definition.properties && definition.properties.keys().map((key) => {
return definition.properties.get(key).name;
})) || [];
constructorArgs = constructorArgs
.map(ref => {
return ref.name;
})
.filter(name => {
return !!name;
});

const properties =
(definition.properties &&
definition.properties.keys().map(key => {
return definition.properties.get(key).name;
})) ||
[];

this.dependencyMap.set(identifier, {
name: typeof definition.path !== 'string' ? definition.path.name : identifier,
name:
typeof definition.path !== 'string'
? definition.path.name
: identifier,
scope: definition.scope,
constructorArgs,
properties,
Expand Down

0 comments on commit c3e15b3

Please sign in to comment.