项目作者: eggjs

项目描述 :
AOP plugin for eggjs, add DI, AOP support.
高级语言: TypeScript
项目地址: git://github.com/eggjs/egg-aop.git
创建时间: 2018-03-15T06:38:39Z
项目社区:https://github.com/eggjs/egg-aop

开源协议:MIT License

下载


egg-aop

NPM version
build status
Test coverage
David deps
Known Vulnerabilities
npm download

Add DI, AOP support for eggjs.

DI

Quick overview

  1. import { Service, Context } from 'egg';
  2. import { context, lazyInject } from 'egg-aop';
  3. @context() // or @application()
  4. export class TestService extends Service {
  5. get() {
  6. /* code */
  7. }
  8. }
  9. export class Controller {
  10. @lazyInject()
  11. private testService: TestService;
  12. demo() {
  13. this.testService.get();
  14. }
  15. }

API

decorators

  • @context(keyType?: any)

    Declaration of life cycle of an instance, is context level. You can provide a class type or from metadata by TypeScript emit.

  • @application(keyType?: any)

    Declaration of life cycle of an instance, is context level. You can provide a class type or from metadata by TypeScript emit.

  • @inject(keyType?: any)

    Inject component when the class is instantiated.

  • @lazyInject(keyType?: any)

    Inject component when accessing the property.

functions

  • getInstance<T = any>(clsType: any, app: any, ctx: any): T

    You can use this function to manually get the component instance.

  • setCreateInstanceHook(func: CreateInstanceHookFunction)

    You can use this function to interception every new component instance.

    type CreateInstanceHookFunction = (instance: any, app: any, ctx?: any) => any;

typeLoader

typeLoader is an instance of IocContext, it stores all type’s classes. You can use this to affect DI behavior.

AOP

Quick overview

  1. function logging(type: string) {
  2. return aspect({
  3. // before method running
  4. before: (context) => { /* log code */ },
  5. // after method running
  6. after: (context) => { /* log code */ },
  7. // when method throw error
  8. onError: (context) => { /* log code */ },
  9. })
  10. }
  11. class DemoService {
  12. @logging('create')
  13. createData() {
  14. /* code */
  15. }
  16. }
  17. /* FunctionContext type define */
  18. export interface FunctionContext<T = any> {
  19. readonly inst: T;
  20. readonly functionName: string;
  21. args: any[];
  22. ret: any;
  23. err: Error;
  24. }

API

functions

  • aspect<T = any>(point: AspectPoint<T> = {})

    You can use this to intercept method, this function provides before / after / error cross-sections.

    1. interface AspectPoint<T = any> {
    2. before?: (context: FunctionContext<T>) => void;
    3. after?: (context: FunctionContext<T>) => void;
    4. error?: (context: FunctionContext<T>) => void;
    5. }

    The param context is the function’s execution context. It includes inst / args / ret. You can replace them to affect the function execution.