<!-- PROJECT LOGO --> <br /> <div align="center"> <a href="https://github.com/toss/nestjs-aop"> <img src="https://toss.tech/wp-content/uploads/2022/11/tech-article-nest-js-02.png" alt="Logo" height="200"> </a>

A way to gracefully apply AOP to nestjs
Use nestjs managed instances in any decorators gracefully
English | 한국어
``sh`
npm install @toss/nestjs-aop
pnpm add @toss/nestjs-aop
yarn add @toss/nestjs-aop
#### 1. Import AopModule
`typescript`
@Module({
imports: [
// ...
AopModule,
],
})
export class AppModule {}
#### 2. Create symbol for LazyDecorator
`typescript`
export const CACHE_DECORATOR = Symbol('CACHE_DECORATOR');
#### 3. Implement LazyDecorator using nestjs provider
metadata is the second parameter of createDecorator.
`typescript
@Aspect(CACHE_DECORATOR)
export class CacheDecorator implements LazyDecorator
constructor(private readonly cache: Cache) {}
wrap({ method, metadata: options }: WrapParams
return (...args: any) => {
let cachedValue = this.cache.get(...args);
if (!cachedValue) {
cachedValue = method(...args);
this.cache.set(cachedValue, ...args);
}
return cachedValue;
};
}
}
`
#### 4. Add LazyDecoratorImpl to providers of module
`typescript`
@Module({
providers: [CacheDecorator],
})
export class CacheModule {}
#### 5. Create decorator that marks metadata of LazyDecorator
options can be obtained from the warp method and used.
`typescript`
export const Cache = (options: CacheOptions) => createDecorator(CACHE_DECORATOR, options)
#### 6. Use it!
`typescript`
export class SomeService {
@Cache({
// ...options(metadata value)
})
some() {
// ...
}
}
`typescript
import { Test } from '@nestjs/testing';
const module = await Test.createTestingModule({
// ...
}).compile();
await module.init();
``