pointyhat
pointyhat

Reputation: 596

class-validator/class-transformer (nestjs): validating, then dropping a property

The context of the question is a nestjs app, where I'd like to transform a request payload to a different shape, and along with that, verify a certain property on the payload, but then remove it after validation. So, a request payload of:

{ "reqType": "foo", "source": "001", "target": "xyz"}

would be validated iff reqType == "foo", then potentially mapped (source->from, target->to), so that the resulting business object is sth like:

{from: "001", to: "xyz"}

Any hints on how that can be done, using a single annotated DTO?

Thanks

Upvotes: 0

Views: 113

Answers (1)

username_jj
username_jj

Reputation: 275

You can declare a factory function in your dto and invoke it in controller, for example:

import { Body, Controller, Post } from '@nestjs/common'
import { IsString } from 'class-validator'

export type MyCustomType =
  | Dto
  | {
      reqType: string
      from: string
      to: string
    }

export class Dto {
  @IsString() // IsEnum() if this is enum
  reqType: string

  @IsString()
  soure: string

  @IsString()
  target: string

  transformToBusinessObj(): MyCustomType {
    // transform to business obj
    if (this.reqType === 'foo') {
      return {
        reqType: this.reqType,
        from: this.soure,
        to: this.target,
      }
    }

    // for other reqType, return original dto
    return this
  }
}

@Controller()
export class MyController {
  @Post()
  myEndpoint(@Body() dto: Dto) {
    const businessObj = dto.transformToBusinessObj()

    // calling to your business service layer....
    // e.g. return myService.execute(businessObj)
  }
}

Upvotes: 0

Related Questions