Skip to content

plainToClass Transform ignored when nested is a newable (decimal.js problem and solution) #1270

@shotokan

Description

@shotokan

Description

I am triying to transform from decimal.js to string or number using plainToClass function and Transform decorator but the TransformOperationExecution is trying tu create a new Decimal instance without passing a valuen to the Decimal constructor and it throws an exception. This happens with any object that receives a value in its constructor apparently.

image

My solution was to create a class that inherits from Decimal and use it in typeorm and Transform.

export class DecimalPatch extends Decimal {
  constructor(value?: any) {
    super(value || 0);
  }
}

// This is used in Typeorm
export class DecimalTransformer implements ValueTransformer {
  /**
   * Used to marshal Decimal when writing to the database.
   */
  to(decimal?: DecimalPatch): string | undefined {
    return decimal?.toString();
  }

  /**
   * Used to unmarshal Decimal when reading from the database.
   */
  from(data: string): DecimalPatch {
    return new DecimalPatch(data);
  }
}

// Transform decorator

  @Type(() => DecimalPatch)
  @Transform(
    ({ value }) => {
      return value.toFixed.(2) ;
    },
    { toClassOnly: true },
  )
  readonly amount!: string;

Minimal code-snippet showcasing the problem

else if (targetType) {
       newValue = new targetType();
 }

// a solution that I have found but it is not very useful
else if (value[valueKey] instanceof Function) {
    subValue = value[valueKey](); --> Comment out this line
}

Expected behavior

It could be able to catch the error or avoid the current behavior but the solution should be done in decimal.js which is in another repository.

Actual behavior

An exception is thrown

Metadata

Metadata

Assignees

No one assigned

    Labels

    status: needs triageIssues which needs to be reproduced to be verified report.type: fixIssues describing a broken feature.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions