Skip to content

Commit

Permalink
fix(common): fallback to empty string for enums when validating (swc)
Browse files Browse the repository at this point in the history
  • Loading branch information
kamilmysliwiec committed Nov 21, 2024
1 parent 5064d9b commit a3aceff
Showing 1 changed file with 20 additions and 3 deletions.
23 changes: 20 additions & 3 deletions packages/common/pipes/validation.pipe.ts
Original file line number Diff line number Diff line change
Expand Up @@ -116,11 +116,12 @@ export class ValidationPipe implements PipeTransform<any> {
: value;
}
const originalValue = value;
value = this.toEmptyIfNil(value);
value = this.toEmptyIfNil(value, metatype);

const isNil = value !== originalValue;
const isPrimitive = this.isPrimitive(value);
this.stripProtoKeys(value);

let entity = classTransformer.plainToClass(
metatype,
value,
Expand Down Expand Up @@ -208,8 +209,24 @@ export class ValidationPipe implements PipeTransform<any> {
return value;
}

protected toEmptyIfNil<T = any, R = any>(value: T): R | {} {
return isNil(value) ? {} : value;
protected toEmptyIfNil<T = any, R = any>(
value: T,
metatype: Type<unknown> | object,
): R | {} {
if (!isNil(value)) {
return value;
}
if (
typeof metatype === 'function' ||
(metatype && 'prototype' in metatype && metatype.prototype?.constructor)
) {
return {};
}
// Builder like SWC require empty string to be returned instead of an empty object
// when the value is nil and the metatype is not a class instance, but a plain object (enum, for example).
// Otherwise, the error will be thrown.
// @ref https://github.com/nestjs/nest/issues/12680
return '';
}

protected stripProtoKeys(value: any) {
Expand Down

0 comments on commit a3aceff

Please sign in to comment.