Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NestJS pipe Joi.validate() (is not a function)

Tags:

nestjs

hapi.js

I try to use Joi validator on NestJS with pipe.

https://docs.nestjs.com/pipes#object-schema-validation

import * as Joi from '@hapi/joi';
import { PipeTransform, Injectable, ArgumentMetadata, BadRequestException } from '@nestjs/common';

@Injectable()
export class JoiValidationPipe implements PipeTransform {
  constructor(
    private readonly schema: Joi.ObjectSchema,
  ) {}

  transform(value: any, metadata: ArgumentMetadata) {
    const { error } = Joi.validate(value, this.schema);

    if (error) {
      throw new BadRequestException('Validation failed');
    }

    return value;
  }
}

It doesn't work properly.

TypeError: Joi.validate is not a function

like image 714
pirmax Avatar asked Dec 11 '22 02:12

pirmax


2 Answers

Use schema.validate in place of Joi.validate, for example:

const schema = Joi.object({
    name: Joi.string().min(3).required()
});
const result = schema.validate(req.body);

or for more info go to https://hapi.dev/family/joi/?v=16.1.8

like image 179
ankita kumari Avatar answered Dec 31 '22 09:12

ankita kumari


I have made an PR to update the https://docs.nestjs.com and it looks like it is already deployed, so you can refer to it.

@hapijs/joi deprecated Joi.validate with version 16 and you have to call .validate directly on schema.

like image 27
Marek Urbanowicz Avatar answered Dec 31 '22 08:12

Marek Urbanowicz