Skip to content

Instantly share code, notes, and snippets.

@paulozullu
Last active December 7, 2022 01:54
Show Gist options
  • Save paulozullu/4290bc3332a82c76e8b7b087e9f88ab7 to your computer and use it in GitHub Desktop.
Save paulozullu/4290bc3332a82c76e8b7b087e9f88ab7 to your computer and use it in GitHub Desktop.
Node.js tips

1 - Default timezone in whole NestJS app

Date.prototype.toJSON = () => {
    return moment(this)
      .tz('America/Sao_Paulo')
      .format('YYYY-MM-DD HH:mm:ss.SSS');
  };

2- Install RabbitMQ locally with docker

docker pull bitnami/rabbitmq
docker run -d --name rabbitmq -p 5672:5671 -p 15672:15672 bitnami/rabbitmq:latest

3 - Add enum validation pipe in NestJS

import { BadRequestException, Injectable, PipeTransform } from '@nestjs/common';
import { isDefined, isEnum } from 'class-validator';

@Injectable()
export class EnumValidationPipe implements PipeTransform<string, Promise<any>> {
  constructor(private enumEntity: any) {}
  transform(value: string): Promise<any> {
    if (isDefined(value) && isEnum(value, this.enumEntity)) {
      return this.enumEntity[value];
    } else {
      const errorMessage = `The value ${value} is not valid. See the acceptable values: ${Object.keys(
        this.enumEntity,
      ).map((key) => this.enumEntity[key])}`;
      throw new BadRequestException(errorMessage);
    }
  }
}

In the controller simply add @Query('type', new EnumValidationPipe(myEnum)) type: myEnum)

4 - Case insensitive search with mongoose

const userExists = await Users.exists({ username: { '$regex': username, $options: 'i' } })

5 - Validate ObjectId with JOI

const paramsValidator = Joi.object({
  partnerPremiumId: Joi.string()
    .regex(/^[0-9a-fA-F]{24}$/)
    .message('O id informado está em formato inválido. Deve ser um oid.')
    .required()

})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment