Skip to main content

Quick start

Nicolas T.Less than 1 minuteGuideinstallation

Quick start

Installation

npm i @aspectjs/common @aspectjs/core

Configuration

AspectJS is based on the tc39 experimental decorators draft 2open in new window. Support for this feature have to be enabled in your 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.

import { AnnotationFactory } from '@aspectjs/common';

// Create an annotation
export const LogErrors = new AnnotationFactory('demo').create(
  function LogErrors() {},
);

2. Create your own aspect

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

import { getWeaver } from '@aspectjs/core';

getWeaver().enable(new LogErrorsAspect());

4. Use the annotation in your code

@LogErrors()
export class Hello {
  hello: string;

  constructor(hello: string = 'hello') {
    this.hello = hello;
  }

  @LogErrors()
  sayHello(who: string = 'world') {
    throw new Error(`${this.hello} ${who}`);
  }
}