0.2.6 • Published 2 years ago

@launchgood/common v0.2.6

Weekly downloads
-
License
MIT
Repository
github
Last release
2 years ago

nestjs-common

Common models, filters, & other goodies for use with Nest.js

AMQP Typed Client

Configure

Requires an RMQ_URL to be defined in your config via env variable or .env, etc.

Import It

import { Module } from '@nestjs/common';
import { CommonModule } from '@launchgood/common';

@Module({
  imports: [CommonModule],
  exports: [CommonModule],
})
export class YourModule {}

Use It

import { Injectable } from '@nestjs/common';
import { TypedRpcClientService } from '@launchgood/common';
import { SomeType } from './some-type';

@Injectable()
export class LedgerService {
  constructor(private client: TypedRpcClientService) {}

  public async doSomething(): Promise<SomeType> {
    const someType = await this.client.request<SomeType>({
      exchange: 'some-exchange',
      routingKey: 'some-routing-key',
      type: SomeType,
    });
  }
}

General Exception Filter for RPC

import { Controller, UseFilters, UsePipes } from '@nestjs/common';
import {
  MessageHandlerErrorBehavior,
  RabbitRPC,
  RabbitSubscribe,
  RabbitPayload,
} from '@golevelup/nestjs-rabbitmq';
import { ValidationPipe } from '@nestjs/common';
import { GeneralExceptionFilter } from '@launchgood/common';
import { SomeService } from './services';
import { SomeType, SomeOtherType } from './models';

@Controller()
export class SomeController {
  constructor(private service: SomeService) {}

  @RabbitRPC({
    exchange: 'some-service',
    routingKey: 'write',
    queue: 'some-service',
    errorBehavior: MessageHandlerErrorBehavior.ACK,
  })
  @UsePipes(new ValidationPipe({ transform: true })) // <-- this transforms and validates the JSON from AMQP based on annotations
  @UseFilters(new GeneralExceptionFilter()) // <--- this line adds handling for errors to your RPC
  async write(
    @RabbitPayload() someType: SomeType,
  ): Promise<SomeOtherType> {
    return await this.service.doSomething(someType);
  }
}