paradox-save-parser-frontend/src/services/SaveParserBackendService.ts

68 lines
1.9 KiB
TypeScript

export interface UploadSaveResponse {
id: string
}
export interface SaveStatusResponse {
id: string
game: string
status: string
uploadDateTime: string
}
export class SaveParserBackendService {
private API_BASE = '/api/proxy/parserBackend'
private async tryGetResponseJson(res: Response): Promise<string> {
try {
const body = await res.json()
return JSON.stringify(body)
} catch {}
return ''
}
async uploadSave(game: string, file: File): Promise<UploadSaveResponse> {
const url = `${this.API_BASE}/uploadSave?game=${encodeURIComponent(game)}`
const response = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/octet-stream',
},
body: file,
})
if (!response.ok) {
throw new Error(`Failed to upload save: ${response.statusText} ${await this.tryGetResponseJson(response)}`)
}
return await response.json()
}
async getSaveStatus(id: string): Promise<SaveStatusResponse> {
const url = `${this.API_BASE}/getSaveStatus?id=${encodeURIComponent(id)}`
const response = await fetch(url)
if (!response.ok) {
throw new Error(
`Failed to get save status: ${response.statusText} ${await this.tryGetResponseJson(response)}`
)
}
return await response.json()
}
async getParsedSave(id: string): Promise<Record<string, any>> {
const url = `${this.API_BASE}/getParsedSave?id=${encodeURIComponent(id)}`
const response = await fetch(url)
if (!response.ok) {
throw new Error(
`Failed to get parsed save: ${response.statusText} ${await this.tryGetResponseJson(response)}`
)
}
return await response.json()
}
}
export const saveParserBackendService = new SaveParserBackendService()