import { HttpClient, HttpErrorResponse } from '@angular/common/http'; import { inject, Injectable } from '@angular/core'; import { firstValueFrom } from 'rxjs'; import { CLOUD_FUNCTION_BASE_URL } from './admin.constants'; import { AdminSessionService } from './admin-session.service'; import { CloudEnvelope, LegacyCloudEnvelope } from './admin.models'; export class CloudFunctionError extends Error { constructor(message: string, readonly status = 0, readonly payload?: unknown) { super(message); } } @Injectable({ providedIn: 'root' }) export class CloudFunctionsService { private readonly http = inject(HttpClient); private readonly sessions = inject(AdminSessionService); async admin(operation: string, params: Record = {}): Promise { const token = this.sessions.session()?.sessionToken; if (!token) throw new CloudFunctionError('管理员会话已失效', 401); try { const envelope = await firstValueFrom(this.http.post>( `${CLOUD_FUNCTION_BASE_URL}/xiaoshu/admin/gateway`, { token, params: { operation, ...params } }, )); if (!envelope.success) throw new CloudFunctionError(envelope.message || envelope.error || '云函数执行失败'); return envelope.data; } catch (error) { if (error instanceof CloudFunctionError) throw error; if (error instanceof HttpErrorResponse) { const payload = error.error as { error?: string; message?: string } | null; if (error.status === 401 || error.status === 403) this.sessions.logout(); throw new CloudFunctionError(payload?.message || payload?.error || error.message, error.status, payload); } throw new CloudFunctionError(error instanceof Error ? error.message : '未知云函数错误'); } } async app(action: string, params: Record = {}): Promise { const token = this.sessions.session()?.sessionToken; if (!token) throw new CloudFunctionError('管理员会话已失效', 401); try { const envelope = await firstValueFrom(this.http.post>( `${CLOUD_FUNCTION_BASE_URL}/xiaoshu/app/gateway`, { token, params: { action, ...params } }, )); if (envelope.retcode === -1) throw new CloudFunctionError(envelope.retmsg || '云函数执行失败'); return envelope.result; } catch (error) { if (error instanceof CloudFunctionError) throw error; if (error instanceof HttpErrorResponse) { const payload = error.error as { error?: string; message?: string; retmsg?: string } | null; if (error.status === 401 || error.status === 403) this.sessions.logout(); throw new CloudFunctionError(payload?.retmsg || payload?.message || payload?.error || error.message, error.status, payload); } throw new CloudFunctionError(error instanceof Error ? error.message : '未知云函数错误'); } } }