Nestjs-create custom json response from entity class



我正在使用typeorm和MySQL。我的实体存储不同类型的运动数据,如足球、田径 ->100 米、200 米、400 米。

在获取调用中,我希望按游戏类型对数据进行分组,即田径或足球,并希望创建嵌套的 JSON,如下所示

JSON 格式:{

"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"}
]
}

我的实体类是这样的:

@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
}

在服务中,我编写了这样的代码来获取竞赛表中的所有数据

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

const competitions = await qb.getMany();

获取结果表单数据库后,我希望按 gameType 列对数据进行分组并将其作为嵌套 json 发送。

请指导我

谢谢大家

您可以循环访问结果集并以这种方式对结果进行分组

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;
}, {})
});

相关内容

最新更新