|
| 1 | +import axios from 'axios' |
| 2 | +import { env } from '@/utils/env' |
| 3 | +import { appConfig } from '@/app/app-config' |
| 4 | +import type { UnifiedAccessPlatformFailureDto } from './unified-access.dto' |
| 5 | +import type { |
| 6 | + UnifiedAccessMethod, |
| 7 | + UnifiedAccessPlatformFailure, |
| 8 | + UnifiedAccessResult, |
| 9 | +} from './unified-access.types' |
| 10 | + |
| 11 | +/** |
| 12 | + * Standalone axios instance for Unified Access calls. |
| 13 | + * |
| 14 | + * Uses X-Aether-Api-Key (not the console bearer token) and must |
| 15 | + * handle arbitrary upstream responses without TML-SDK normalisation. |
| 16 | + */ |
| 17 | +const uaHttp = axios.create({ |
| 18 | + baseURL: env.apiBaseUrl, |
| 19 | + timeout: env.requestTimeoutMs, |
| 20 | + headers: { 'X-App-Id': appConfig.appId }, |
| 21 | + // Prevent axios from rejecting non-2xx so we can classify ourselves |
| 22 | + validateStatus: () => true, |
| 23 | + // Receive binary-safe data |
| 24 | + responseType: 'arraybuffer', |
| 25 | +}) |
| 26 | + |
| 27 | +function isPlatformFailure( |
| 28 | + status: number, |
| 29 | + contentType: string, |
| 30 | + body: unknown, |
| 31 | +): body is UnifiedAccessPlatformFailureDto { |
| 32 | + if (![400, 401, 404, 503].includes(status)) return false |
| 33 | + if (!contentType.includes('application/json')) return false |
| 34 | + if (typeof body !== 'object' || body === null) return false |
| 35 | + return 'failureType' in body |
| 36 | +} |
| 37 | + |
| 38 | +function parseContentType(raw?: string): string { |
| 39 | + return (raw ?? 'application/octet-stream').split(';')[0].trim().toLowerCase() |
| 40 | +} |
| 41 | + |
| 42 | +function collectHeaders(headers: Record<string, unknown>): Record<string, string> { |
| 43 | + const out: Record<string, string> = {} |
| 44 | + for (const [k, v] of Object.entries(headers)) { |
| 45 | + if (typeof v === 'string') out[k] = v |
| 46 | + } |
| 47 | + return out |
| 48 | +} |
| 49 | + |
| 50 | +export async function invokeUnifiedAccess( |
| 51 | + apiCode: string, |
| 52 | + method: UnifiedAccessMethod, |
| 53 | + apiKey: string, |
| 54 | + payload?: string, |
| 55 | + extraHeaders?: Record<string, string>, |
| 56 | +): Promise<UnifiedAccessResult> { |
| 57 | + const url = `v1/access/${encodeURIComponent(apiCode)}` |
| 58 | + const hasBody = !['GET', 'DELETE'].includes(method) |
| 59 | + |
| 60 | + const headers: Record<string, string> = { |
| 61 | + 'X-Aether-Api-Key': apiKey, |
| 62 | + ...extraHeaders, |
| 63 | + } |
| 64 | + |
| 65 | + if (hasBody && payload) { |
| 66 | + headers['Content-Type'] = headers['Content-Type'] ?? 'application/json' |
| 67 | + } |
| 68 | + |
| 69 | + const response = await uaHttp.request({ |
| 70 | + url, |
| 71 | + method: method.toLowerCase(), |
| 72 | + headers, |
| 73 | + data: hasBody && payload ? payload : undefined, |
| 74 | + }) |
| 75 | + |
| 76 | + const status: number = response.status |
| 77 | + const ct = parseContentType(response.headers['content-type']) |
| 78 | + const rawHeaders = collectHeaders(response.headers) |
| 79 | + const buffer: ArrayBuffer = response.data |
| 80 | + |
| 81 | + // Try to decode as text first for JSON / text classification |
| 82 | + let textDecoded: string | undefined |
| 83 | + try { |
| 84 | + textDecoded = new TextDecoder('utf-8').decode(buffer) |
| 85 | + } catch { |
| 86 | + // binary - leave undefined |
| 87 | + } |
| 88 | + |
| 89 | + // Check platform failure |
| 90 | + if (textDecoded && ct.includes('application/json')) { |
| 91 | + try { |
| 92 | + const parsed = JSON.parse(textDecoded) |
| 93 | + if (isPlatformFailure(status, ct, parsed)) { |
| 94 | + const failure: UnifiedAccessPlatformFailure = { |
| 95 | + code: parsed.code, |
| 96 | + message: parsed.message, |
| 97 | + failureType: parsed.failureType, |
| 98 | + traceId: parsed.traceId, |
| 99 | + apiCode: parsed.apiCode, |
| 100 | + } |
| 101 | + return { kind: 'platform-failure', status, contentType: ct, platformFailure: failure, rawHeaders } |
| 102 | + } |
| 103 | + // Non-failure JSON |
| 104 | + return { kind: 'json', status, contentType: ct, jsonBody: parsed, rawHeaders } |
| 105 | + } catch { |
| 106 | + // malformed JSON - fall through to text |
| 107 | + } |
| 108 | + } |
| 109 | + |
| 110 | + if (textDecoded && ct.startsWith('text/')) { |
| 111 | + return { kind: 'text', status, contentType: ct, textBody: textDecoded, rawHeaders } |
| 112 | + } |
| 113 | + |
| 114 | + // Binary fallback |
| 115 | + return { |
| 116 | + kind: 'binary', |
| 117 | + status, |
| 118 | + contentType: ct, |
| 119 | + blobBody: new Blob([buffer], { type: ct }), |
| 120 | + rawHeaders, |
| 121 | + } |
| 122 | +} |
0 commit comments