Skip to content
Myr

Advertise the shortcut media type on the attempt that produced the response

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Sindre Sorhus · committed by Sindre Sorhus · parent 6b67569 · Browse files · 2 files+31 added−1 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

2 files+31 added−1 removed

  • tests:+26 added−0 removed
  • other:+5 added−1 removed

2 files+31 added−1 removed

modified:source/core/Ky.ts+5 added-1 removed
396 unmodified lines
397 continue;398 }399400 result[type] = async (schema?: StandardSchemaV1) => {401 // `#fetch()` replaces `ky.request` with the clone it prepares for a possible retry, so a shortcut called402 // after the request was dispatched would otherwise advertise its media type on that clone, which is only403 // sent if a retry happens, instead of on the attempt that produced the response.404 const acceptRequest = ky.#originalRequest ?? ky.request;405 // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing402 ky.request.headers.set('accept', ky.request.headers.get('accept') || mimeType);406 acceptRequest.headers.set('accept', acceptRequest.headers.get('accept') || mimeType);407408 const response = await result;409410 // `ky.stop` from a `beforeRetry` hook resolves the request with no response at all. Reading a body
1140 unmodified lines
modified:test/main.ts+26 added
4260 unmodified lines
42614262 t.is(contexts[0], '{"nested":{"value":1}}');4263 t.deepEqual(context, {nested: {value: 2}});4264});42654266// `#fetch()` replaces `ky.request` with the clone prepared for a possible retry, so a shortcut called after the4267// request was dispatched advertised its media type on that clone, which is only sent if a retry happens, instead of4268// on the attempt that produced the response the caller reads.4269test('a body shortcut called after dispatch does not advertise its media type on the retry', async t => {4270 const accepts: string[] = [];4271 let attempts = 0;42724273 const promise = ky('https://example.com', {4274 retry: {limit: 1, delay: () => 20},4275 async fetch(request) {4276 attempts++;4277 accepts.push(request.headers.get('accept') ?? 'none');4278 return attempts === 1 ? new Response('{"ok":true}', {status: 500}) : new Response('{"ok":true}');4279 },4280 });42814282 // Dispatch the first attempt, then ask for JSON while the retry delay is still running.4283 await new Promise(resolve => {4284 setTimeout(resolve, 5);4285 });4286 t.is(JSON.stringify(await promise.json()), '{"ok":true}');42874288 t.is(attempts, 2);4289 t.deepEqual(accepts, ['none', 'none']);4290});