rwadurian/backend/services/authorization-service/src/infrastructure/external/identity-service.client.ts

101 lines
2.8 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { Injectable, Logger, OnModuleInit } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import axios, { AxiosInstance } from 'axios';
/**
* 用户信息接口
*/
export interface UserInfo {
userId: string;
accountSequence: string;
nickname: string;
avatarUrl?: string;
}
/**
* Identity Service HTTP 客户端
* 用于从 identity-service 获取用户信息
* 注意:系统间通信使用 accountSequence 作为标识符
*/
@Injectable()
export class IdentityServiceClient implements OnModuleInit {
private readonly logger = new Logger(IdentityServiceClient.name);
private httpClient: AxiosInstance;
private readonly baseUrl: string;
private readonly enabled: boolean;
constructor(private readonly configService: ConfigService) {
this.baseUrl = this.configService.get<string>('IDENTITY_SERVICE_URL') || 'http://rwa-identity-service:3000';
this.enabled = this.configService.get<boolean>('IDENTITY_SERVICE_ENABLED') !== false;
}
onModuleInit() {
this.httpClient = axios.create({
baseURL: this.baseUrl,
timeout: 10000,
headers: {
'Content-Type': 'application/json',
},
});
this.logger.log(`[INIT] IdentityServiceClient initialized: ${this.baseUrl}, enabled: ${this.enabled}`);
}
/**
* 批量获取用户信息(按 accountSequence
*/
async batchGetUserInfoBySequence(accountSequences: string[]): Promise<Map<string, UserInfo>> {
const result = new Map<string, UserInfo>();
if (!this.enabled || accountSequences.length === 0) {
return result;
}
try {
this.logger.debug(`[HTTP] POST /internal/users/batch - ${accountSequences.length} users`);
const response = await this.httpClient.post<UserInfo[]>(
`/api/v1/internal/users/batch`,
{ accountSequences },
);
if (response.data && Array.isArray(response.data)) {
for (const user of response.data) {
result.set(user.accountSequence, user);
}
}
this.logger.debug(`[HTTP] Got ${result.size} users info`);
} catch (error) {
this.logger.error(`[HTTP] Failed to batch get user info:`, error);
}
return result;
}
/**
* 获取单个用户信息(按 accountSequence
*/
async getUserInfoBySequence(accountSequence: string): Promise<UserInfo | null> {
if (!this.enabled) {
return null;
}
try {
this.logger.debug(`[HTTP] GET /internal/users/${accountSequence}`);
const response = await this.httpClient.get<UserInfo>(
`/api/v1/internal/users/${accountSequence}`,
);
if (response.data) {
return response.data;
}
} catch (error) {
this.logger.error(`[HTTP] Failed to get user info for ${accountSequence}:`, error);
}
return null;
}
}