Files
persona-lenz/apps/web/src/lib/api.ts
T

76 lines
2.3 KiB
TypeScript

import type {
AnalysisJobStatusDto,
AnalysisRequestAcceptedDto,
AnalysisRequestDto,
PlayerAnalysisDto,
SimilarPlayersDto,
} from '@persona-lenz/shared'
import { resolveApiUrl } from '../config'
export class ApiError extends Error {
readonly status: number
constructor(status: number, message: string) {
super(message)
this.name = 'ApiError'
this.status = status
}
}
async function request<T>(path: string, init?: RequestInit): Promise<T> {
let response: Response
try {
response = await fetch(resolveApiUrl(path), init)
} catch {
throw new ApiError(0, '서버에 연결하지 못했어요. 네트워크를 확인하고 다시 시도해 주세요.')
}
if (!response.ok) {
const body = (await response.json().catch(() => null)) as { message?: string | string[] } | null
const message = Array.isArray(body?.message) ? body.message[0] : body?.message
throw new ApiError(response.status, message ?? `요청에 실패했어요. (${response.status})`)
}
return (await response.json()) as T
}
export function requestAnalysis(payload: AnalysisRequestDto): Promise<AnalysisRequestAcceptedDto> {
return request('/api/analysis/request', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload),
})
}
export function getJobStatus(jobId: string): Promise<AnalysisJobStatusDto> {
return request(`/api/analysis/jobs/${encodeURIComponent(jobId)}`)
}
export function getLatestAnalysis(puuid: string): Promise<PlayerAnalysisDto> {
return request(`/api/players/${encodeURIComponent(puuid)}/analysis/latest`)
}
export function getSimilarPlayers(puuid: string): Promise<SimilarPlayersDto> {
return request(`/api/players/${encodeURIComponent(puuid)}/similar-players`)
}
const LAST_REQUEST_KEY = 'pl:last-analysis-request'
export function saveLastRequest(payload: AnalysisRequestDto): void {
try {
sessionStorage.setItem(LAST_REQUEST_KEY, JSON.stringify(payload))
} catch {
// storage 불가 환경에서도 분석 자체는 계속 진행
}
}
export function loadLastRequest(): AnalysisRequestDto | null {
try {
const raw = sessionStorage.getItem(LAST_REQUEST_KEY)
if (!raw) return null
const parsed = JSON.parse(raw) as AnalysisRequestDto
if (!parsed.gameName || !parsed.tagLine) return null
return parsed
} catch {
return null
}
}