import { Injectable, Logger } from '@nestjs/common'; import { HttpService } from '@nestjs/axios'; import { ConfigService } from '@nestjs/config'; import { firstValueFrom } from 'rxjs'; import { IIdentityServiceClient } from '../../domain/services/leaderboard-calculation.service'; /** * Identity Service 客户端实现 * * 从身份服务获取用户信息 */ @Injectable() export class IdentityServiceClient implements IIdentityServiceClient { private readonly logger = new Logger(IdentityServiceClient.name); private readonly baseUrl: string; constructor( private readonly httpService: HttpService, private readonly configService: ConfigService, ) { this.baseUrl = this.configService.get('IDENTITY_SERVICE_URL', 'http://localhost:3001'); } async getUserSnapshots(userIds: bigint[]): Promise> { const result = new Map(); if (userIds.length === 0) { return result; } try { const response = await firstValueFrom( this.httpService.post(`${this.baseUrl}/api/users/batch`, { userIds: userIds.map(id => id.toString()), }), ); const users = response.data.data || []; for (const user of users) { result.set(user.userId.toString(), { userId: BigInt(user.userId), nickname: user.nickname || user.username || '用户' + user.userId.slice(-4), avatar: user.avatar || null, accountNo: user.accountNo || null, }); } } catch (error) { this.logger.error('获取用户信息失败', error); // 为找不到的用户创建默认快照 for (const userId of userIds) { if (!result.has(userId.toString())) { result.set(userId.toString(), { userId, nickname: '用户' + userId.toString().slice(-4), avatar: null, accountNo: null, }); } } } return result; } }