niran
niran

Reputation: 1980

Nestjs-create custom json response from entity class

I am using typeorm and MySQL. My entity stores different types of sports data like Football, Athletics->100m,200m,400m.

In the the get call I want group data by gameType that is athletics or football and want create nested JSON like below

JSON format: {

  "footBall":[
       {"location":"use",gameType:"footbal", "goals":2,"result":"won"},
       {"location":"use",gameType:"footbal", "goals":1,"result":"draw"}
    ],

    "athletics":[
         {"location":"poland",gameType:"athletics", gameSubType:"100m", "rank":2,"result":"first place"},
         {"location":"ireland",gameType:"athletics", gameSubType:"200m", "rank":1,"result":"second place"}
      ]

}

My entity class is like this:

  @Entity('competition')
export class CompetitionEntity {
    @PrimaryGeneratedColumn()
    id:Number

    @Column({ type: 'timestamp', default: () => "CURRENT_TIMESTAMP"})
    date:Date

    @Column()
    location:String

    @Column()
    rank:Number

    @Column()
    eventType: string

    @Column()
    minutes: number

    @Column()
    seconds: number

    @Column()
    miliseconds: number

    @Column()
    gameType: string  //it can take values like athletics or football or baseball etc

    @Column()
    gameSubType: string //it can take value like 100m, 200m, relay etc
}

In service I have written code like this to get all data in competition table

    const qb = await getRepository(CompetitionEntity)
        .createQueryBuilder('competition')


    const competitions = await qb.getMany();

After getting result form database, I want group data by gameType column and send it as nested json.

Please guide me on this

Thank you all

Upvotes: 0

Views: 3945

Answers (1)

Yevhenii
Yevhenii

Reputation: 1703

You can iterate over resulted set and group you result in this way

const competitions = await qb.getMany().then(results => {
  return results.reduce((prev, curr) => {
    if (!prev[curr.gameType]) {
      prev[curr.gameType] = [];
    }
    prev[curr.gameType].push(curr);
    return prev;
  }, {})
});

Upvotes: 2

Related Questions