how can I get my dto of relations in typeOrm?

6.1k Views Asked by At

how can I get my dto of relations in typeOrm?

I have nationals and provinces

I use plainToClass of 'class-transformer' and get dto of national

I want get dto of relations ( provinces )

{
    "code": "Manchester",
    "name": "Manchester",
    "displayOrder": "0",
    "nationalId": 1,
    "national": {
      "id": 1,
      "name": "England",
      "code": "England",
      "displayOrder": "1",
      "createdAt": "2021-08-04T07:44:13.186Z",
      "updatedAt": "2021-08-04T07:44:13.186Z",
      "version": "0"
    }
},

my dto of relations :

export class NationalDto {
    name: string;
    code: string;
    displayOrder: number;
}

I want get like:

{
    "code": "Manchester",
    "name": "Manchester",
    "displayOrder": "0",
    "nationalId": 1,
    "national": {
      "name": "England",
      "code": "England",
      "displayOrder": "1"
    }
},

This my code in repository :

async findAll(): Promise<Province[]> {
    return await this.find({
        relations : ["nationals"]
    })
}
2

There are 2 best solutions below

0
Vahid Najafi On

You can combine both DTOs. For example:

// national dto
export class NationalDto {
    name: string;
    code: string;
    displayOrder: number;
}
// provinces dto
export class ProvinceDto {
    name: string;
    code: string;
    displayOrder: number;
    national: NationalDto
}

In some cases, you can use nestjs mapped types in order to reuse dtos.

0
Irfandy Jip On

You can do the following

Your DTO that you want to use in another DTO.

export class NationalDto {
  name: string;
  code: string;
  displayOrder: number;
}

The DTO that consumes above DTO

import { Expose, Type } from "class-transformer"
import { NationalDto } from "./NationalDto"

export class ProvinceDto {
  name: string;
  code: string;
  displayOrder: number;
  
  @Type(() => NationalDto)
  @Expose()
  national: NationalDto
}