homemanager-fe/src/utils/jfetch.ts

57 lines
1.3 KiB
TypeScript

import deepUnref from './deep-unref';
export class JFetchResponse<T> {
constructor(
public statusCode: number,
public headers: Headers,
public data: T
) {}
}
export class JFetchError {
constructor(
public statusCode: number,
public headers: Headers,
public data: any
) {}
}
export default async function jfetch<T = any>(
url: string,
opts: Record<string, unknown> & {
returnType?: 'blob' | 'json' | 'arraybuffer';
}
) {
const { returnType } = opts;
if (opts['body'] && typeof opts['body'] === 'object') {
opts['body'] = JSON.stringify(opts['body']);
opts['headers'] = {
...deepUnref(opts['headers'] || {}),
'Content-Type': 'application/json',
};
}
const response = await fetch(url, {
...(opts as Record<string, unknown>),
});
let data!: T;
if (!returnType || returnType === 'json') {
data = await response.json();
}
if (returnType === 'arraybuffer') {
data = (await response.arrayBuffer()) as T;
}
if (returnType === 'blob') {
data = (await response.blob()) as T;
}
if (response.status < 200 || response.status > 299) {
throw new JFetchError(response.status, response.headers, data);
}
return new JFetchResponse<T>(response.status, response.headers, data);
}