Skip to content

Commit 4a5e6ae

Browse files
committed
feat(query): ability to disable body parsing
1 parent 1a841e3 commit 4a5e6ae

1 file changed

Lines changed: 8 additions & 4 deletions

File tree

packages/query/src/index.ts

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -123,6 +123,8 @@ export interface RequestOptions {
123123
retry?: number;
124124
/** Milliseconds to wait before the next request is retried. Subsequent requests will be multiplied by `Math.LOG2E`. A random jitter of 50% of the `retryMs` value is applied. */
125125
retryMs?: number;
126+
/** Make an attempt to parse the body. If the content type of the response is application/json, body is a JSON object, text otherwise. Set to false if you need to read the response yourself. Defaults to true. */
127+
parseBody?: boolean;
126128
}
127129

128130
function parseRequestArguments(args: unknown[]): [path: string, options: RequestOptions] {
@@ -143,7 +145,7 @@ export async function request<T>(
143145
input: string,
144146
args: RequestOptions = { },
145147
): Promise<{ response: Response; body?: T; error?: Error }> {
146-
const { retry = 3, retryMs = 250, signal, queryParameters = {} } = args;
148+
const { retry = 3, retryMs = 250, signal, parseBody = true, queryParameters = {} } = args;
147149
const qs = new URLSearchParams(queryParameters);
148150
const body = args.body?.constructor === Object ? JSON.stringify(args.body) : args.body;
149151
const res = await fetch(`${qs}` ? `${input}?${qs}` : input, {
@@ -163,10 +165,11 @@ export async function request<T>(
163165
signal,
164166
).then(() => request(input, { ...args, retryMs: retryMs * Math.LOG2E, retry: retry - 1 }));
165167

166-
const text = await res.text();
168+
if (parseBody === false) return { response: res };
169+
167170
try {
168-
const body = text.length ? JSON.parse(text) : text;
169-
return { response: res, body: body };
171+
const body = res.headers.get('content-type')?.includes('application/json') ? res.json() : res.text();
172+
return { response: res, body: await body };
170173
} catch (err: unknown) {
171174
return { response: res, error: err instanceof Error ? err : new Error('unknown error') };
172175
}
@@ -373,6 +376,7 @@ export function useQuery<T>(...args: unknown[]): QueryResponse<T> {
373376
if (cancelled) return;
374377
if (res.ok) {
375378
setResponse(body);
379+
setError(undefined);
376380
setStatus('success');
377381
} else {
378382
if (err) setError(err);

0 commit comments

Comments
 (0)