6 Star 16 Fork 5

散漫的水元素 / aspects-js

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
README.ZH-CN.md 4.14 KB
一键复制 编辑 原始数据 按行查看 历史
wangmiao 提交于 2020-05-13 14:29 . 1.0.2 pre

aspects-js

aspects-js

英文

在nodejs中使用面向切面的变成

1.安装

只需要使用NPM进行安装

$ npm install --save aspects-js

2.使用

需要在你的入口文件的最开始的位置引入aspects-js

require('aspects-js');

3.添加切面

添加一个切面,这个切面的定义将写在一个新的文件中 首先,需要在这个切面定义文件的最开始的位置引入aspects-js中的Aspect接口

//文件: testAspect.js
const { Aspect } = require('aspects-js');

其次,在文件中声明自定义的切面类继承Aspect接口,并重写pointcut属性的get方法返回切面表达式,同时可以重写面向切点处理的一些方法

//文件: testAspect.js
class TestAspect extends Aspect {
    get pointcut() { return '*.do*()' },
    before() { console.log('this is for before join point') },
    after() { console.log('this is for after join point') }
}

然后,需要将这个自定义的切面类的实例导出

//文件: testAspect.js
module.exports = new TestAspect();

最后,在项目的入口文件(在需要被切面类加载之前)加载指定的切面类实例

//文件: entry.js
require('./testAspect.js');

现在,所有的后续加载的类在执行起方法时将会被自定义的切面类进行切面

4.API(提供的接口/类)

Aspect接口

interface Aspect {
    readonly pointcut: Pointcut | string | ((joinPoint: JoinPoint) => boolean);
    readonly order: number;

    after(joinPoint: JoinPoint, result: any, error: Error);
    afterReturn(joinPoint: JoinPoint, result: any): any;
    afterThrow(joinPoint: JoinPoint, error: Error): void;
    before(joinPoint: JoinPoint):void;
    around(joinPoint: JoinPoint): any;
}

JoinPoint

class JoinPoint {
    readonly type: Class;
    readonly fun: Function;
    readonly thisArg: any;
    readonly target: any;
    readonly args: any[];

    proceed(...args: any[]): any;
}

Pointcut

class Pointcut {
    constructor(pointcut: string);

    matches(joinPoint: JoinPoint): boolean;
}

5.切面表达式

1.标准表达式

"ClassName.FunctionName()"

2.execution关键字

"execution(ClassName.FunctionName())"

3.within关键字

"within(ClassName)"

4.参数表达式

"FunctionName(..)"
"FunctionName(Type1,Type2)"
"FunctionName(Type1,..,Type2)"

4.运算符与通配符

> * 匹配多个字符 通配符

"*Service.do*()"

匹配所有以Service结尾的类型中的以do开头的方法

> ? 匹配一个字符 通配符

"you?.do?()"

> + 针对名称的 或 运算

"within(Test1+Test2)"

匹配Test1Test2中所有的方法

> |,|| 逻辑 或 运算符

"within(Test1)|within(Test2)"

匹配Test1Test2中所有的方法

> &,&& 逻辑 且 运算符

"within(Test1)&abc"

匹配Test1中的abc方法

> ! 逻辑 非 运算符

"!within(Test)"

匹配所有不在Test类中的方法

> () 括号运算符 (用于逻辑)

提升括号内部表达式的优先级

> () 方法调用 运算符

"abc()"
"abc(..)"

匹配所有的名称为abc的方法

"abc(Type1)"

匹配所有的名称为abc且在执行时只传入了一个类型为Type1的参数的方法

> , 参数分割 运算符

"*(Type1,Type2)"

匹配所有执行时传入类型依次为Type1Type2两个参数的所有方法

> . 属性 运算符

"Test.abc()"

匹配Test类中的abc方法

> .. Multiple arguments operator for arguments

匹配连续的多个参数类型

5.其他

Aspects接口的order属性

此属性用于控制切面的执行顺序,值越小优先级越高

6.更新与发布

1.0.2 未发布

增加pointcut可以使用函数作为值 接口Aspects增加属性order,用于控制切面的执行顺序

1.0.1

在pointcut中使用AST的方式代替正则

JavaScript
1
https://gitee.com/wm123450405/aspects-js.git
git@gitee.com:wm123450405/aspects-js.git
wm123450405
aspects-js
aspects-js
master

搜索帮助