import deepUnref from './deep-unref'; export class JFetchResponse { 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( url: string, opts: Record & { 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), }); 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(response.status, response.headers, data); }