Skip to content

plainToClass: Transform ignored when nested is a newable #1138

@jbdemonte

Description

@jbdemonte

Description

When a plain object contains a newable instance, plainToClass / plainToInstance try to new it before processing to the Transform decorator, and when the new throw, it just make it not usable.

Use case: I'm using prisma with a postgres database, and with Decimal columns. It deeply use decimal.js to map this datatype.

Problem is when trying to cast the "plain" object from the DB to an instance, even if the field is decorated with a Transformer, it try first to new the Decimal field and, that point throw because the constructor needs a parameter

Minimal code-snippet showcasing the problem
code sandbox

import { Decimal } from "decimal.js";
import { Transform, plainToInstance } from "class-transformer";

class Item {
  name!: string;

  @Transform(({ value }) => (value as Decimal).toNumber())
  price!: number;
}

const itemFromPrisma = {
  name: "sticker",
  price: new Decimal(2.55)
};

const instance = plainToInstance(Item, itemFromPrisma);

Expected behavior

It should not try to new the deep object when a decorator is set

Actual behavior

It try to instanciate the nested constructor

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