Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 15 additions & 8 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,11 @@ export type ErrorResponse = {
message: string
}

const isErrorResponse = (data: unknown): data is ErrorResponse => {
const isObject = typeof data === 'object' && data !== null
return isObject && 'code' in data && 'message' in data
}

function replaceParam(str: string, key: string, value: string): string {
return str.replace(new RegExp(`\\{${key}\\}`, 'g'), value)
}
Expand Down Expand Up @@ -51,16 +56,18 @@ export async function fetchData<T>(url: string, body?: unknown): Promise<T> {
}

const resp = await fetch(url, options)
const json = await resp.json()
let json

if (!resp.ok) {
let errTxt = ''
try {
const err = json as ErrorResponse
errTxt = `${err.code}: ${err.message}`
} catch (e) {
errTxt = resp.statusText
try {
json = await resp.json()
} catch {
if (resp.headers && resp.headers.get('content-length') !== '0') {
throw new Error(`Invalid response content: ${resp.statusText}`)
}
}

if (!resp.ok) {
const errTxt = isErrorResponse(json) ? `${json.code}: ${json.message}` : resp.statusText
throw new Error(errTxt)
}

Expand Down