47 lines
1017 B
TypeScript
47 lines
1017 B
TypeScript
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;
|
|
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);
|
|
}
|