Nestjs入门

依赖注入几种方式。

封装为库

以pulsar的使用为例。特点:需要注入配置,创建client单例。

实现方式:在module中定义static register方法,返回DynamicModule。

  static register(options: any): DynamicModule {
    return {
      // 封装的模块的名字,即当前模块的名字
      module: PulsarModule,
      imports: options.imports || [],
      providers: [
        {
          // 可以在其它模块使用此字符串注入
          provide: 'PULSAR_CLIENT_URL',
          useFactory: options.useFactory,
          inject: options.inject,
        },
      ],
    };
  }

然后在对应service中提供client的方法:

import { Injectable, Inject } from '@nestjs/common';

import {
  Client,
  Consumer,
  Producer,
  ProducerOpts,
  SubscribeOpts,
} from 'pulsar-client';

@Injectable()
export class PulsarService {
  pulsar: Client;
  constructor(@Inject('PULSAR_CLIENT_URL') private url) {
    this.pulsar = new Client({ serviceUrl: url });
  }

  async buildConsumer(options: SubscribeOpts): Promise<Consumer> {
    return this.pulsar.subscribe(options);
  }

  async buildProducer(options: ProducerOpts): Promise<Producer> {
    return this.pulsar.createProducer(options);
  }

  async closeArr(arr: Consumer[] | Producer[]) {
    if (!arr || !arr.length) return;
    for (const ele of arr) ele.close();
  }

  async close(consumers?: Consumer[], producers?: Producer[]) {
    this.closeArr(consumers);
    this.closeArr(producers);
    if (this.pulsar) {
      this.pulsar.close();
    }
  }
}

关于pulsar,一个消息中间件,已经封装为一个npm库,欢迎使用,star。https://www.npmjs.com/package/nestjs-pulsar

Leave a Reply

Your email address will not be published. Required fields are marked *