Quick start
Less than 1 minuteGuideinstallation
Quick start
Installation
npm
npm i @aspectjs/common @aspectjs/core
yarn
yarn add @aspectjs/common @aspectjs/core
Configuration
AspectJS is based on the tc39 experimental decorators draft 2. Support for this feature have to be enabled in your tsconfig.json
:
tsconfig.json
{
"compilerOptions": {
"experimentalDecorators": true
}
}
How to use
1. Create your own annotation
Simply put, an annotation is an ES decorator with no behavior. Annotations act as markers to identify specific elements in your codebase where an aspect can be applied.
log-errors.annotation.ts
import { AnnotationFactory } from '@aspectjs/common';
// Create an annotation
export const LogErrors = new AnnotationFactory('demo').create(
function LogErrors() {},
);
2. Create your own aspect
log-errors.aspect.ts
import { AfterThrow, AfterThrowContext, Aspect, on } from '@aspectjs/core';
@Aspect()
export class LogErrorsAspect {
@AfterThrow(
on.classes.withAnnotations(LogErrors),
on.methods.withAnnotations(LogErrors),
)
logAround(context: AfterThrowContext, error: Error) {
console.error(
`${context.target}(${context.args.join(',')}) throwed error ${error}`,
);
// Propagate the error
throw error;
}
}
3. Enable an aspect
aop.ts
import { getWeaver } from '@aspectjs/core';
getWeaver().enable(new LogErrorsAspect());
4. Use the annotation in your code
hello.ts
@LogErrors()
export class Hello {
hello: string;
constructor(hello: string = 'hello') {
this.hello = hello;
}
@LogErrors()
sayHello(who: string = 'world') {
throw new Error(`${this.hello} ${who}`);
}
}