📝Pipe - JoiValidation

This pipe is responsible for validating the request body.

Import

import { JoiValidationPipe } from 'niro-health';

Create DTO & Schema

dto/create.ts
export class CreateUserDto {
  email: string;
  username: string;
  password: string;
}
dto/schemas/create.ts
import * as Joi from 'joi';

import { CreateUserDto } from './dto/create';

export const CreateUserSchema = Joi.object<CreateUserDto>({
  email: Joi.string().email().required(),
  username: Joi.string().required(),
  password: Joi.string().required(),
});

Create Parser

parsers/index.ts
import { Injectable } from '@nestjs/common';
import type { RecursivePartial } from 'niro-health';
import type { User } from './entities';

@Injectable()
export class UsersParser {
  toJSON(user: User): RecursivePartial<User> {
    return {
      id: user.id,
      email: user.tag,
      username: user.value,
      createdAt: user.createdAt,
      updatedAt: user.updatedAt,
    };
  }
}

Method of Use

users.controller.ts
import {
  HttpException,
  HttpStatus,
  Controller,
  Get,
  Post,
  Body,
  Patch,
  Query,
  Param,
  Delete,
  UsePipes,
  Inject,
} from '@nestjs/common';

import { JoiValidationPipe } from 'niro-health';

import { UsersService } from 'users.service';

import type { CreateUserDto } from './dto/create';

import { CreateUserSchema } from './dto/schemas/create.joi';

import { UsersParser } from './parsers';

@Controller('api/users')
export class UsersController {
  constructor(
    @Inject('IUsersService')
    private readonly usersService: UsersService,
    @Inject('IUsersParser')
    private readonly usersParser: UsersParser,
  ) {}

  @Post()
  @UsePipes(new JoiValidationPipe(CreateUserSchema))
  async create(@Body() createUserDto: CreateUserDto) {
    const key = await this.usersService.create(
      createUserDto,
    );

    if (key instanceof Error)
      throw new HttpException(key.message, HttpStatus.FORBIDDEN);

    return this.usersParser.toJSON(key);
  }
}

Last updated