whefter / joi-class-decorators

MIT License
7 stars 1 forks source link

Сheck if schema exists in class metadata #1

Closed stepanzabelin closed 2 years ago

stepanzabelin commented 2 years ago

Hello! Thanks for your hard work! I found that there is no way to check if schema is set inside DTO

getClassSchema(Dto)

always returns Joi schema

Could you add a check function ?

hasClassSchema(type: Constructor,  { group }: { group?: JoiValidationGroup } = {}): boolean

Example

hasClassSchema(Dto) // true
hasClassSchema(Dto, {group: 'CREATE'}) // false
whefter commented 2 years ago

Thank you. This could be implemented, but I'm curious about the use case. Could you give me your example use case?

stepanzabelin commented 2 years ago

You asked a good question :)

initially i wanted to make using joi validation optional

export class CarDto {
  readonly id!: number;
  readonly name!: string;
}

 getClassSchema(CarDto).validate({ id: 5, name: 'Tesla' }) 
 // -> Error: "id" is not allowed

Because "allowUnknown" is false by default and and Dto still requires the JoiSchemaOptions decorator

I assumed the following solution:

function validate(dto, data) {
  if(!hasClassSchema(dto)) {
    return data;
  }

  const {error, value} = getClassSchema(dto).validate(data) 
  if(error)  {
    throw error;
  }
  return value
}

I thought a little and realized that optional using validation is not logical. It should be configured I think that this issue is not relevant for me more, thanks for the quick reply

whefter commented 2 years ago

It's true that even a class without any annotations will produce a Joi schema with the default options. I can see where that would cause some confusion, though the question here is whether this isn't an edge case - to validate using a class schema, you have to explicitely get its schema to pass it to Joi, so presumably you've thought about which classes will be "validated".

Thanks for your input. I'll leave this as is for now, if more people ask about this so there is more information about use cases, it can be re-evaluated.