auerbachb
auerbachb

Reputation: 947

NestJS Typeorm filter relations from reponse

How can one ensure only the entity itself and not it's relations are returned by TypeOrm when using Repository.save(myEntity)?

given this example entity

@Entity()
export class Flavor {
  @ManyToMany(
    type => Coffee,
    coffee => coffee.flavors,
  )
  coffees: Coffee[];
}
@Entity()
export class Coffee {
  @JoinTable()
  @ManyToMany(
    type => Flavor,
    flavor => flavor.coffees,
  )
  flavors: Flavor[];
}

and this example service


  async create(createCoffeeDto: CreateCoffeeDto) {
    const flavors = await Promise.all(
      createCoffeeDto.flavors.map(name => this.preloadFlavorByName(name)),
    );

    const coffee = this.coffeeRepository.create({
      ...createCoffeeDto,
      flavors,
    });
    return this.coffeeRepository.save(coffee);
  }

how can I filter the response so it only returns the Coffee entity and not the Flavor entity. Eg this

{
  "id": 0,
  "name": "string",
  "brand": "string",
  "recommendations": 0,
}

not this

{
  "id": 0,
  "name": "string",
  "brand": "string",
  "recommendations": 0,
  "flavors": [
    {
      "id": 0,
      "name": "string",
      "coffees": [
        null
      ]
    }
  ]
}

Upvotes: 0

Views: 1815

Answers (1)

Bruno Lipovac
Bruno Lipovac

Reputation: 447

One way of doing this would be to use class transformer. https://github.com/typestack/class-transformer

First you define your response class like this:

export class CreateCoffeeResponseDto {
   id: number;
   name: string;
   brand: string;
   recommendations: number;
}

And then when returning it from the service you can:

return plainToClass(CoffeeCreateResponseDto, await this.coffeeRepository.save(coffee));

Also, you can do it all with .save() call if you put { cascade: true } options object on your relations. https://typeorm.io/#/relations/cascades

Upvotes: 2

Related Questions