Repository URL to install this package:
|
Version:
7.1.2-patch-delete ▾
|
import { ResponseExtended } from '../typings'
import { config } from '../config'
import { toPrettyError } from './toPrettyError'
import { isJsonContentType } from './isJsonContentType'
async function parseJsonBodyOrText(res: ResponseExtended) {
try {
if (typeof res.json === 'function') {
const body = await res.json()
res.data = body
} else {
const data = await res.text()
res.data = JSON.parse(data)
}
} catch (parseError) {
config.get('logger').error(parseError)
res.prettyError = parseError
}
}
async function handleErrorResponse(res: ResponseExtended) {
res.prettyError = new Error(res.statusText)
// check if the response was JSON, and if so, better the error
if (isJsonContentType(res) === true) {
// attempt to parse json body to use as error message
await parseJsonBodyOrText(res)
const prettyError = toPrettyError(res)
if (prettyError) {
res.prettyError = prettyError
}
}
}
export async function decorateResponseByParsingBody(
res: ResponseExtended | Promise<ResponseExtended> | Promise<Response>
) {
const asPromise = res as Promise<ResponseExtended>
const asRes = res as ResponseExtended
if (
typeof asPromise.then === 'function' &&
typeof asRes.json !== 'function'
) {
const response = await asPromise
const decorated = await decorateResponseByParsingBody(response)
return decorated
}
if (!asRes.ok) {
await handleErrorResponse(asRes)
} else if (isJsonContentType(asRes) === true) {
await parseJsonBodyOrText(asRes)
} else {
const body = await asRes.text()
asRes.data = body
}
return asRes
}
export async function fromResponseToResult(res: ResponseExtended) {
decorateResponseByParsingBody(res)
return res
}