Skip to content

feat: allow casting strings to boolean #626

Closed as not planned
Closed as not planned
@QuanticPotatoes

Description

@QuanticPotatoes

Hi, I use class-transformer on NestJS and a cast problem occured during the conversion of the request payload.

Example :

{
"page": "1",
"limit": "1",
"isAnnotate": "false"
}

We got :

{
page: 1,
limit: 1,
isAnnotate: true
}

The defining class is :

class ArticleQuery {
  page: number;

  limit: number;

  isAnnotate?: boolean
}

https://github.com/nestjs/nest/blob/master/packages/common/pipes/validation.pipe.ts#L96
When the plainToClass function was executed such as :

/*
* metatype => ArticleQuery
* value => { page: "1", limit: "1",  isAnnotate: "false" }
* transformOptions => { enableImplicitConversion: true }
* /
classTransformer.plainToClass(metatype, value, this.transformOptions);

After a little digging, i found the caused into the function transform :
https://github.com/typestack/class-transformer/blob/develop/src/TransformOperationExecutor.ts#L108

    } else if (targetType === Boolean && !isMap) {
      if (value === null || value === undefined) return value;
      return Boolean(value);

So i made a patch locally to solve the issue :

    } else if (targetType === Boolean && !isMap) {
      if (value === null || value === undefined) return value;
      return value === "true";

Is it an attended behavior from the function to not convert a string "true"/"false" to a Boolean ?

Current version: 0.4.0

Best regards

Metadata

Metadata

Assignees

No one assigned

    Labels

    status: duplicateIssue is being tracked already in another issue.type: featureIssues related to new features.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions