Recipes
About 2 minexamples
Recipes
Find annotations on an given target
get-annotations.ts
import { getAnnotations } from '@aspectjs/common';
import { OneToMany } from './annotations';
import './entities/post.entity';
import { Post } from './entities/post.entity';
import './entities/user.entity';
import { User } from './entities/user.entity';
console.log(`All annotations found : ${getAnnotations().all().find()}`);
// @aspectjs:demo:Entity on class Post
// @aspectjs:demo:Entity on class User
// @aspectjs:demo:BeforePersist on method Post.setPublishDate
// @aspectjs:demo:Column on property Post.title
// @aspectjs:demo:Column on property Post.body
// @aspectjs:demo:Column on property Post.publishDate
// @aspectjs:demo:Column on property User.title
// @aspectjs:demo:Column on property User.body
// @aspectjs:demo:Column on property User.posts
// @aspectjs:demo:OneToMany on property User.posts
console.log(
`All annotations found on classes: ${getAnnotations().onClass().find()}`,
);
// @aspectjs:demo:Entity on class Post
// @aspectjs:demo:Entity on class User
console.log(
`All annotations found on the User class: ${getAnnotations()
.onClass(User)
.find()}`,
);
// @aspectjs:demo:Entity on class User
console.log(
`All annotations found on methods of the Post class: ${getAnnotations()
.onMethod(Post)
.find()}`,
);
// @aspectjs:demo:BeforePersist on method Post.setPublishDate
console.log(
`OneToMany() annotations found: ${getAnnotations(OneToMany).all().find()}`,
);
// @aspectjs:demo:OneToMany on property User.posts
User.entity.ts
import { Column, Entity, OneToMany } from '../annotations';
import { Post } from './post.entity';
@Entity()
export class User {
@Column()
title: string;
@Column()
body: string;
@Column()
@OneToMany()
posts: Post[];
}
Post.entity.ts
import { BeforePersist, Column, Entity } from '../annotations';
@Entity()
export class Post {
@Column()
title: string;
@Column()
body: string;
@Column()
publishDate: Date;
@BeforePersist()
setPublishDate() {
this.publishDate = new Date();
}
}
Log the execution time of a method
main.ts
import { getWeaver } from '@aspectjs/core';
import { Monitored } from './annotations/monitored.annotation';
import { MonitoredAspect } from './aspects/monitored.aspect';
getWeaver().enable(MonitoredAspect);
class UserResource {
@Monitored()
fetchUsers() {
// simutate an http fetch with some delay
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(['Joe', 'Jack', 'William', 'Avrell']);
}, 500);
});
}
}
async function main() {
const userResource = new UserResource();
console.log(`${await userResource.fetchUsers()}`);
// method UserResource.fetchUsers resolved after 503 ms
// Joe,Jack,William,Avrell
}
main();
monitored.aspect.ts
import { Around, AroundContext, Aspect, JoinPoint, on } from '@aspectjs/core';
import { Monitored } from '../annotations/monitored.annotation';
@Aspect()
export class MonitoredAspect {
@Around(on.methods.withAnnotations(Monitored))
logTime(ctxt: AroundContext, jp: JoinPoint, jpArgs: unknown[]) {
const t = new Date().getTime();
try {
const returnedValue = jp(...jpArgs);
if (returnedValue instanceof Promise) {
// return a new promise that logs the execution time
return returnedValue.then(
(r) => {
console.log(
`${ctxt.target} resolved after ${new Date().getTime() - t} ms`,
);
return r;
},
(r) => {
console.log(
`${ctxt.target} rejected after ${new Date().getTime() - t} ms`,
);
return r;
},
);
} else {
console.log(
`${ctxt.target} returned after ${new Date().getTime() - t} ms`,
);
return returnedValue;
}
} catch (e) {
console.log(
`${ctxt.target} errored after ${new Date().getTime() - t} ms`,
);
// throw the original error
throw e;
}
}
}
monitored.annotation
import { AnnotationKind } from '@aspectjs/common';
import { ANNOTATION_FACTORY } from './annotation-factory';
export const Monitored = ANNOTATION_FACTORY.create(
AnnotationKind.METHOD,
function Monitored() {},
);
Get the parameters of an annotation in an advice
deprecated.aspect.ts
import { Aspect, Before, BeforeContext, on } from '@aspectjs/core';
import { AnnotationFactory } from '@aspectjs/common';
// create the annotation
const af = new AnnotationFactory('aspectjs');
export const Deprecated = af.create(function (message?: string) {});
@Aspect()
export class DeprecatedAspect {
@Before(on.any.withAnnotations(Deprecated))
logDeprecated(context: BeforeContext) {
// find the @Deprecated annotation on the current target
const deprecated = context.annotations(Deprecated).find()[0];
// get the arguments of the annotation
const options: string | undefined = deprecated.args[0];
// ...
}
}