如何在Node.js中合并参与者列表与头像接口的返回结果
问题:将用户头像信息合并到参与者列表
现有service.ts中根据ID获取关联用户列表的代码如下:
async getId(id:number){ // 根据ID获取参与者列表 let participants = await this.participantRepo.findById(id) // 遍历每个参与者,尝试获取其头像 for (const participant of participants) { let result = await this.profilePictureService.getprofilePicture(participant.user); // result中会返回该用户的头像(如果存在) } // 拆分内部/外部参与者 const [internalParticipants, externalParticipants] = _partition( participants, (p: CampParticipants) => p.participantRoleId !== ParticipantRoleEnum.External ); return { internalParticipants, externalParticipants, }; }
相关示例数据
- 参与者列表示例响应:
{ "internalParticipants": [ { "id": 515, "userId": 126, "participantRoleId": 1, "user": { "id": 126, "firstName": "Test1", "lastName": "Test", "mail": "test@home.com" } }, { "id": 515, "userId": 1219, "participantRoleId": 2, "user": { "id": 1219, "firstName": "Rob", "lastName": "const", "mail": "rob.const@home.com" } } ], "externalParticipants": [] }
- 头像接口示例响应(仅userId为126的用户存在头像):
{ "photoName": "profile-picture.png", "buffer": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAABDgAAAQ4CAYAAADsEGyPAAAAAXNSR0IArc" }
预期输出
需要将头像信息合并到对应参与者对象中,得到如下结果:
{ "internalParticipants": [ { "id": 515, "userId": 126, "participantRoleId": 1, "user": { "id": 126, "firstName": "Test1", "lastName": "Test", "mail": "test@home.com" }, "photoName": "profile-picture.png", "buffer": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAABDgAAAQ4CAYAAADsEGyPAAAAAXNSR0IArc" }, { "id": 515, "userId": 1219, "participantRoleId": 2, "user": { "id": 1219, "firstName": "Rob", "lastName": "const", "mail": "rob.const@home.com" } } ], "externalParticipants": [] }
解决方案
直接修改循环逻辑,将头像接口返回的属性合并到对应参与者对象中即可,同时增加空值判断避免无效属性:
修改后的完整代码:
async getId(id:number){ // 获取参与者列表 let participants = await this.participantRepo.findById(id) // 遍历参与者并合并头像信息 for (const participant of participants) { const profilePic = await this.profilePictureService.getprofilePicture(participant.user); // 仅当存在有效头像数据时,合并属性到参与者对象 if (profilePic) { // 方式1:逐个赋值 participant.photoName = profilePic.photoName; participant.buffer = profilePic.buffer; // 方式2:一次性合并所有属性 // Object.assign(participant, profilePic); } } const [internalParticipants, externalParticipants] = _partition( participants, (p: CampParticipants) => p.participantRoleId !== ParticipantRoleEnum.External ); return { internalParticipants, externalParticipants, }; }
关键说明
- 属性合并:通过直接赋值或
Object.assign,将头像接口返回的photoName和buffer添加到对应参与者对象中 - 空值过滤:增加
if (profilePic)判断,确保没有头像的参与者不会被添加undefined属性 - 性能优化可选:如果想要并行请求所有头像以提升速度,可以替换循环为
Promise.all:
// 并行请求优化版 await Promise.all(participants.map(async (participant) => { const profilePic = await this.profilePictureService.getprofilePicture(participant.user); if (profilePic) { Object.assign(participant, profilePic); } }));
内容的提问来源于stack exchange,提问作者userrj_vj_051620
相关产品推荐
相关产品推荐

