Repository URL to install this package:
|
Version:
0.0.3 ▾
|
export function fromFetchAndResponseToObj<Body = any>(response: Response, body: Body) {
return {
type: response.type,
headers: response.headers,
ok: response.ok,
status: response.status,
statusText: response.statusText,
data: body,
}
}
export async function fetchJson<Body = {[key: string]: any}>(url: string | Request, options?: RequestInit) {
try {
const result = await fetch(url, options)
const json = await result.json()
return fromFetchAndResponseToObj<Body>(result, json)
} catch (fetchException) {
console.error('fetchJson failed', fetchException)
return {
error: fetchException,
}
}
}
export async function fetchText<BodyType extends string = string>(url: string | Request, options?: RequestInit) {
try {
const result = await fetch(url, options)
const text = await result.text()
return fromFetchAndResponseToObj<BodyType>(result, text as any)
} catch (fetchException) {
console.error('fetchText failed', fetchException)
return {
error: fetchException,
}
}
}
export async function fetchDynamic<BodyType extends string = string>(url: string | Request, options?: RequestInit) {
try {
const result = await fetch(url, options)
// 1st, json
try {
const json = await result.json()
return fromFetchAndResponseToObj<BodyType>(result, json as any)
} catch (jsonException) {
// 2nd, text
const text = await result.text()
return fromFetchAndResponseToObj<BodyType>(result, text as any)
}
// fetch exception, or text
} catch (fetchException) {
console.error('fetchText failed', fetchException)
return {
error: fetchException,
}
}
}