Skip to content
Myr

Fix `beforeRequest` hooks being skipped when a `Request` is returned (#832)

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

authored by Sindre Sorhus · committed by GitHub · parent 6f3d1bd · Browse files · 5 files+524 added−11 removed
This commit

State

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

Diff stats

5 files+524 added−11 removed

  • tests:+514 added−0 removed
  • other:+10 added−11 removed

5 files+524 added−11 removed

modified:source/core/Ky.ts+8 added-9 removed
334 unmodified lines
335336 if (!supportsRequestStreams) {337 throw new Error('Request streams are not supported in your environment. The `duplex` option for `Request` is not available.');338 }339340 this.request = this.#wrapRequestWithUploadProgress(this.request, this.#options.body ?? undefined);339 }340 }341342 #calculateDelay(): number {
339 unmodified lines
682 }683684 if (result instanceof globalThis.Request) {685 this.#assignRequest(result);688 break;686 }687 }688689 const nonRequestOptions = findUnknownOptions(this.request, this.#options);690 const retryRequest = this.#options.retry.limit > 0 ? this.request.clone() : undefined;691 const request = this.#wrapRequestWithUploadProgress(this.request, this.#options.body ?? undefined);692693 // Cloning is done here to prepare in advance for retries.694 // Skip cloning when retries are disabled — cloning a streaming body calls ReadableStream#tee()695 // which buffers the entire stream in memory, causing excessive memory usage for large uploads.697 this.#originalRequest = this.request;698 if (this.#options.retry.limit > 0) {699 this.request = this.#originalRequest.clone();696 this.#originalRequest = request;697 if (retryRequest) {698 this.request = retryRequest;699 }700701 if (this.#options.timeout === false) {703 return this.#options.fetch(this.#originalRequest, nonRequestOptions);702 return this.#options.fetch(request, nonRequestOptions);703 }704705 const remainingTimeout = this.#getRemainingTimeout() ?? this.#options.timeout;706 if (remainingTimeout <= 0) {707 throw new TimeoutError(this.request);708 }709711 return timeout(this.#originalRequest, nonRequestOptions, this.#abortController, {710 return timeout(request, nonRequestOptions, this.#abortController, {711 ...this.#options,712 timeout: remainingTimeout,713 } as TimeoutOptions);714 }
37 unmodified lines
752 }753754 #assignRequest(request: Request): void {755 this.#cachedNormalizedOptions = undefined;757 this.request = this.#wrapRequestWithUploadProgress(request);756 this.request = request;757 }758759 #wrapRequestWithUploadProgress(request: Request, originalBody?: BodyInit): Request {760 if (!this.#options.onUploadProgress || !request.body) {
6 unmodified lines
modified:source/types/hooks.ts+1 added-1 removed
63 unmodified lines
64 This hook enables you to modify the request right before it is sent. Ky will make no further changes to the request after this. The hook function receives a state object with the normalized request, options, and retry count. You could, for example, modify `request.headers` here.6566 The `retryCount` is `0` for the initial request and increments with each retry. This allows you to distinguish between initial requests and retries, which is useful when you need different behavior for retries (e.g., avoiding overwriting headers set in `beforeRetry`).6768 A [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response) can be returned from this hook to completely avoid making an HTTP request. This can be used to mock a request, check an internal cache, etc. An **important** consideration when returning a `Response` from this hook is that all the following hooks will be skipped, so **ensure you only return a `Response` from the last hook**.68 A [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request) can be returned from this hook to replace the outgoing request; remaining hooks will still run with the updated request. A [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response) can be returned to completely avoid making an HTTP request, in which case remaining `beforeRequest` hooks are skipped. This can be used to mock a request, check an internal cache, etc.6970 @example71 ```72 import ky from 'ky';
208 unmodified lines
modified:test/hooks.ts+76 added
9 unmodified lines
10} from '../source/index.js';11import {type Options} from '../source/types/options.js';12import {createHttpTestServer} from './helpers/create-http-test-server.js';1314const withHeader = (request: Request, name: string, value: string) => {15 const headers = new Headers(request.headers);16 headers.set(name, value);17 return new Request(request, {headers});18};1920const createStreamBody = (text: string) => new ReadableStream<Uint8Array>({21 start(controller) {22 controller.enqueue(new TextEncoder().encode(text));23 controller.close();
1124 unmodified lines
1148 t.true(beforeErrorHookCalled);1149 t.true(thrownError instanceof TypeError);1150});11511152test('hooks beforeRequest returning Request continues running remaining hooks', async t => {1153 let capturedRequest: Request | undefined;11541155 await ky.get('https://example.com', {1156 async fetch(request) {1157 capturedRequest = request as Request;1158 return new Response('ok');1159 },1160 hooks: {1161 beforeRequest: [1162 ({request}) => withHeader(request, 'x-hook-1', 'hook-1'),1163 ({request}) => {1164 // Verify hook 2 receives the updated request produced by hook 11165 t.is(request.headers.get('x-hook-1'), 'hook-1');1166 return withHeader(request, 'x-hook-2', 'hook-2');1167 },1168 ],1169 },1170 });11711172 t.truthy(capturedRequest);1173 t.is(capturedRequest!.headers.get('x-hook-1'), 'hook-1');1174 t.is(capturedRequest!.headers.get('x-hook-2'), 'hook-2');1175});11761177test('hooks beforeRequest returning Request then non-returning hook both run', async t => {1178 let capturedRequest: Request | undefined;1179 let hook2Ran = false;11801181 await ky.get('https://example.com', {1182 async fetch(request) {1183 capturedRequest = request as Request;1184 return new Response('ok');1185 },1186 hooks: {1187 beforeRequest: [1188 ({request}) => withHeader(request, 'x-hook-1', 'hook-1'),1189 () => {1190 hook2Ran = true;1191 },1192 ],1193 },1194 });11951196 t.truthy(capturedRequest);1197 t.true(hook2Ran);1198 t.is(capturedRequest!.headers.get('x-hook-1'), 'hook-1');1199});12001201test('hooks beforeRequest returning Request then Response skips HTTP request', async t => {1202 const expectedResponse = 'intercepted';1203 let fetchCalled = false;12041205 const response = await ky.get('https://example.com', {1206 async fetch() {1207 fetchCalled = true;1208 return new Response('should not reach');1209 },1210 hooks: {1211 beforeRequest: [1212 ({request}) => withHeader(request, 'x-hook-1', 'hook-1'),1213 () => new Response(expectedResponse, {status: 200}),1214 ],1215 },1216 }).text();12171218 t.false(fetchCalled);1219 t.is(response, expectedResponse);1220});12211222test('hooks beforeRequest returning Response skips HTTP Request', async t => {1223 const expectedResponse = 'empty hook';12241225 const response = await ky
1942 unmodified lines
modified:test/stream.ts+438 added
67 unmodified lines
68 'Last update should have transferred all bytes',69 );70});7172test('multiple beforeRequest Request hooks do not duplicate upload progress events', async t => {73 const server = await createHttpTestServer(t, {bodyParser: false});74 server.post('/', async (request, response) => {75 response.json(await parseJsonBody<Record<string, unknown>>(request));76 });7778 let completedUploadProgressEvents = 0;79 const payload = {test: 'test'};80 const responseJson = await ky81 .post(server.url, {82 json: payload,83 hooks: {84 beforeRequest: [85 ({request}) => {86 const headers = new Headers(request.headers);87 headers.set('x-hook-1', 'hook-1');88 return new Request(request, {headers});89 },90 ({request}) => {91 const headers = new Headers(request.headers);92 headers.set('x-hook-2', 'hook-2');93 return new Request(request, {headers});94 },95 ],96 },97 onUploadProgress(progress) {98 if (progress.percent === 1) {99 completedUploadProgressEvents++;100 }101 },102 })103 .json<Record<string, unknown>>();104105 t.deepEqual(responseJson, payload);106 t.is(completedUploadProgressEvents, 1);107});108109test('multiple beforeRequest Request hooks do not duplicate upload progress events across retries', async t => {110 const server = await createHttpTestServer(t, {bodyParser: false});111 let requestCount = 0;112 server.post('/', async (request, response) => {113 requestCount++;114 if (requestCount === 1) {115 response.status(500).json({error: 'retry'});116 return;117 }118119 response.json(await parseJsonBody<Record<string, unknown>>(request));120 });121122 const completedUploadProgressEventsPerAttempt: number[] = [];123 const payload = {test: 'retry'};124 const responseJson = await ky125 .post(server.url, {126 json: payload,127 retry: {128 limit: 1,129 methods: ['post'],130 },131 hooks: {132 beforeRequest: [133 ({request}) => {134 completedUploadProgressEventsPerAttempt.push(0);135 const headers = new Headers(request.headers);136 headers.set('x-hook-1', 'hook-1');137 return new Request(request, {headers});138 },139 ({request}) => {140 const headers = new Headers(request.headers);141 headers.set('x-hook-2', 'hook-2');142 return new Request(request, {headers});143 },144 ],145 },146 onUploadProgress(progress) {147 if (progress.percent !== 1) {148 return;149 }150151 const currentAttemptIndex = completedUploadProgressEventsPerAttempt.length - 1;152 completedUploadProgressEventsPerAttempt[currentAttemptIndex]++;153 },154 })155 .json<Record<string, unknown>>();156157 t.deepEqual(responseJson, payload);158 t.deepEqual(completedUploadProgressEventsPerAttempt, [1, 1]);159});160161test('beforeRequest Request replacement preserves upload progress sizing', async t => {162 const server = await createHttpTestServer(t, {bodyParser: false});163 server.post('/', async (request, response) => {164 let totalBytes = 0;165 for await (const chunk of request) {166 totalBytes += chunk.length as number;167 }168169 response.json({receivedBytes: totalBytes});170 });171172 const largeBlob = createLargeBlob(10);173 const progressEvents: Progress[] = [];174 const response = await ky175 .post(server.url, {176 body: largeBlob,177 hooks: {178 beforeRequest: [179 ({request}) => {180 const headers = new Headers(request.headers);181 headers.set('x-hook', '1');182 return new Request(request, {headers});183 },184 ],185 },186 onUploadProgress(progress) {187 progressEvents.push(progress);188 },189 })190 .json<{receivedBytes: number}>();191192 t.true(progressEvents.length >= 2, 'Should produce multiple progress events');193 const nonFinalProgressEvents = progressEvents.filter(progress => progress.percent < 1);194 t.true(nonFinalProgressEvents.length > 0, 'Should include non-final progress events');195 for (const progress of nonFinalProgressEvents) {196 const expectedPercent = progress.transferredBytes / largeBlob.size;197 t.true(progress.percent <= expectedPercent + 0.01, 'Intermediate progress should reflect known body size');198 }199200 const finalProgress = progressEvents.at(-1);201 t.truthy(finalProgress);202 t.is(finalProgress!.percent, 1);203 t.true(finalProgress!.totalBytes > 1024 * 1024);204 t.is(finalProgress!.totalBytes, finalProgress!.transferredBytes);205 t.is(response.receivedBytes, finalProgress!.totalBytes);206});207208test('beforeRequest Request replacement with new body preserves upload progress sizing', async t => {209 const server = await createHttpTestServer(t, {bodyParser: false});210 server.post('/', async (request, response) => {211 let receivedBytes = 0;212 for await (const chunk of request) {213 receivedBytes += chunk.length as number;214 }215216 response.json({receivedBytes});217 });218219 const payload = {initial: true};220 const replacementBody = createLargeBlob(10);221 const progressEvents: Progress[] = [];222 const response = await ky223 .post(server.url, {224 json: payload,225 hooks: {226 beforeRequest: [227 ({request}) => new Request(request, {body: replacementBody}),228 ],229 },230 onUploadProgress(progress) {231 progressEvents.push(progress);232 },233 })234 .json<{receivedBytes: number}>();235236 t.true(progressEvents.length > 0, 'Should produce progress events');237 const expectedSize = replacementBody.size;238 const finalProgress = progressEvents.at(-1);239 t.truthy(finalProgress);240 t.is(finalProgress!.percent, 1);241 t.is(finalProgress!.totalBytes, expectedSize);242 t.is(finalProgress!.transferredBytes, expectedSize);243 t.is(response.receivedBytes, expectedSize);244});245246test('missing content-length still uses original body size for upload progress', async t => {247 const server = await createHttpTestServer(t, {bodyParser: false});248 server.post('/', async (request, response) => {249 let receivedBytes = 0;250 for await (const chunk of request) {251 receivedBytes += chunk.length as number;252 }253254 response.json({receivedBytes});255 });256257 const body = createLargeBlob(10);258 const progressEvents: Progress[] = [];259 const response = await ky260 .post(server.url, {261 body,262 hooks: {263 beforeRequest: [264 ({request}) => {265 request.headers.delete('content-length');266 },267 ],268 },269 onUploadProgress(progress) {270 progressEvents.push(progress);271 },272 })273 .json<{receivedBytes: number}>();274275 t.true(progressEvents.length >= 2, 'Should produce multiple progress events');276 const nonFinalProgressEvents = progressEvents.filter(progress => progress.percent < 1);277 t.true(nonFinalProgressEvents.length > 0, 'Should include non-final progress events');278 t.true(nonFinalProgressEvents[0].percent > 0, 'Non-final progress should use known total size');279280 const finalProgress = progressEvents.at(-1);281 t.truthy(finalProgress);282 t.is(finalProgress!.percent, 1);283 t.is(finalProgress!.totalBytes, body.size);284 t.is(finalProgress!.transferredBytes, body.size);285 t.is(response.receivedBytes, body.size);286});287288test('beforeRequest replacement with smaller body completes upload progress correctly', async t => {289 const server = await createHttpTestServer(t, {bodyParser: false});290 server.post('/', async (request, response) => {291 let receivedBytes = 0;292 for await (const chunk of request) {293 receivedBytes += chunk.length as number;294 }295296 response.json({receivedBytes});297 });298299 const originalBody = createLargeBlob(10);300 const replacementBody = 'small-body';301 const replacementBodySize = Buffer.byteLength(replacementBody);302 const progressEvents: Progress[] = [];303 const response = await ky304 .post(server.url, {305 body: originalBody,306 hooks: {307 beforeRequest: [308 ({request}) => new Request(request, {body: replacementBody}),309 ],310 },311 onUploadProgress(progress) {312 progressEvents.push(progress);313 },314 })315 .json<{receivedBytes: number}>();316317 t.true(progressEvents.length > 0, 'Should produce progress events');318 const nonFinalProgressEvents = progressEvents.filter(progress => progress.percent < 1);319 for (const progress of nonFinalProgressEvents) {320 t.true(progress.percent < 1, 'Intermediate progress should stay below completion');321 }322323 const finalProgress = progressEvents.at(-1);324 t.truthy(finalProgress);325 t.is(finalProgress!.percent, 1);326 t.is(finalProgress!.transferredBytes, replacementBodySize);327 t.is(response.receivedBytes, replacementBodySize);328});329330test('beforeRequest replacement with larger body has monotonic upload progress', async t => {331 const server = await createHttpTestServer(t, {bodyParser: false});332 server.post('/', async (request, response) => {333 let receivedBytes = 0;334 for await (const chunk of request) {335 receivedBytes += chunk.length as number;336 }337338 response.json({receivedBytes});339 });340341 const replacementBody = createLargeBlob(10);342 const progressEvents: Progress[] = [];343 const response = await ky344 .post(server.url, {345 body: 'tiny',346 hooks: {347 beforeRequest: [348 ({request}) => new Request(request, {body: replacementBody}),349 ],350 },351 onUploadProgress(progress) {352 progressEvents.push(progress);353 },354 })355 .json<{receivedBytes: number}>();356357 t.true(progressEvents.length > 0, 'Should produce progress events');358 for (let index = 1; index < progressEvents.length; index++) {359 t.true(progressEvents[index].transferredBytes >= progressEvents[index - 1].transferredBytes, 'Transferred bytes should be monotonic');360 t.true(progressEvents[index].percent >= progressEvents[index - 1].percent, 'Percent should be monotonic');361 }362363 const finalProgress = progressEvents.at(-1);364 t.truthy(finalProgress);365 t.is(finalProgress!.percent, 1);366 t.is(finalProgress!.transferredBytes, replacementBody.size);367 t.is(response.receivedBytes, replacementBody.size);368});369370test('beforeRequest body replacement followed by header hook keeps progress and headers', async t => {371 const server = await createHttpTestServer(t, {bodyParser: false});372 server.post('/', async (request, response) => {373 let receivedBytes = 0;374 for await (const chunk of request) {375 receivedBytes += chunk.length as number;376 }377378 response.json({379 receivedBytes,380 header: request.headers['x-hook-2'],381 });382 });383384 const replacementBody = 'hook-replacement-body';385 const replacementBodySize = Buffer.byteLength(replacementBody);386 const progressEvents: Progress[] = [];387 const response = await ky388 .post(server.url, {389 body: createLargeBlob(10),390 hooks: {391 beforeRequest: [392 ({request}) => new Request(request, {body: replacementBody}),393 ({request}) => {394 const headers = new Headers(request.headers);395 headers.set('x-hook-2', 'true');396 return new Request(request, {headers});397 },398 ],399 },400 onUploadProgress(progress) {401 progressEvents.push(progress);402 },403 })404 .json<{receivedBytes: number; header: string | undefined}>();405406 const finalProgress = progressEvents.at(-1);407 t.truthy(finalProgress);408 t.is(finalProgress!.percent, 1);409 t.is(finalProgress!.transferredBytes, replacementBodySize);410 t.is(response.receivedBytes, replacementBodySize);411 t.is(response.header, 'true');412});413414test('retry with beforeRequest body changes tracks per-attempt upload progress', async t => {415 const server = await createHttpTestServer(t, {bodyParser: false});416 let requestCount = 0;417 server.post('/', async (_request, response) => {418 requestCount++;419 if (requestCount === 1) {420 response.status(500).json({error: 'retry'});421 return;422 }423424 response.status(200).json({ok: true});425 });426427 const firstAttemptBody = 'first-attempt';428 const secondAttemptBody = 'second-attempt-body';429 const firstAttemptBodySize = Buffer.byteLength(firstAttemptBody);430 const secondAttemptBodySize = Buffer.byteLength(secondAttemptBody);431 const eventsByAttempt: Progress[][] = [];432 let currentAttempt = 0;433434 await ky.post(server.url, {435 body: 'initial',436 retry: {437 limit: 1,438 methods: ['post'],439 },440 hooks: {441 beforeRequest: [442 ({request, retryCount}) => {443 currentAttempt = retryCount;444 eventsByAttempt[currentAttempt] = [];445 const body = retryCount === 0 ? firstAttemptBody : secondAttemptBody;446 return new Request(request, {body});447 },448 ],449 },450 onUploadProgress(progress) {451 eventsByAttempt[currentAttempt].push(progress);452 },453 }).json();454455 t.is(eventsByAttempt.length, 2);456 const firstAttemptFinalProgress = eventsByAttempt[0].at(-1);457 const secondAttemptFinalProgress = eventsByAttempt[1].at(-1);458 t.truthy(firstAttemptFinalProgress);459 t.truthy(secondAttemptFinalProgress);460 t.is(firstAttemptFinalProgress!.percent, 1);461 t.is(secondAttemptFinalProgress!.percent, 1);462 t.is(firstAttemptFinalProgress!.transferredBytes, firstAttemptBodySize);463 t.is(secondAttemptFinalProgress!.transferredBytes, secondAttemptBodySize);464 t.is(eventsByAttempt[0].filter(progress => progress.percent === 1).length, 1);465 t.is(eventsByAttempt[1].filter(progress => progress.percent === 1).length, 1);466});467468test('ReadableStream upload emits stable non-final progress and completes once', async t => {469 const server = await createHttpTestServer(t, {bodyParser: false});470 server.post('/', async (request, response) => {471 let receivedBytes = 0;472 for await (const chunk of request) {473 receivedBytes += chunk.length as number;474 }475476 response.json({receivedBytes});477 });478479 const streamBody = new ReadableStream<Uint8Array>({480 start(controller) {481 controller.enqueue(new TextEncoder().encode('chunk-1'));482 controller.enqueue(new TextEncoder().encode('chunk-2'));483 controller.close();484 },485 });486487 const progressEvents: Progress[] = [];488 const response = await ky489 .post(server.url, {490 body: streamBody,491 onUploadProgress(progress) {492 progressEvents.push(progress);493 },494 })495 .json<{receivedBytes: number}>();496497 t.true(progressEvents.length > 0, 'Should emit upload progress');498 const nonFinalProgressEvents = progressEvents.filter(progress => progress.percent < 1);499 t.true(nonFinalProgressEvents.length > 0, 'Should emit non-final progress');500 for (const progress of nonFinalProgressEvents) {501 t.true(progress.percent >= 0 && progress.percent < 1, 'Non-final progress should be within [0, 1)');502 }503504 const completedProgressEvents = progressEvents.filter(progress => progress.percent === 1);505 t.is(completedProgressEvents.length, 1, 'Should complete exactly once');506 const finalProgress = completedProgressEvents[0];507 t.is(finalProgress.transferredBytes, response.receivedBytes);508});509510test('onDownloadProgress cancels original response body', async t => {511 let originalResponse: Response | undefined;512 let didReportProgress = false;513
371 unmodified lines
modified:readme.md+1 added-1 removed
349 unmodified lines
350This hook enables you to modify the request right before it is sent. Ky will make no further changes to the request after this. The hook function receives a state object with the normalized request, options, and retry count. You could, for example, modify the `request.headers` here.351352The `retryCount` is `0` for the initial request and increments with each retry. This allows you to distinguish between initial requests and retries, which is useful when you need different behavior for retries (e.g., avoiding overwriting headers set in `beforeRetry`).353354The hook can return a [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request) to replace the outgoing request, or return a [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response) to completely avoid making an HTTP request. This can be used to mock a request, check an internal cache, etc. An **important** consideration when returning a request or response from this hook is that any remaining `beforeRequest` hooks will be skipped, so you may want to only return them from the last hook.354The hook can return a [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request) to replace the outgoing request (remaining hooks will still run with the updated request). It can also return a [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response) to completely avoid making an HTTP request, in which case remaining `beforeRequest` hooks are skipped. This can be used to mock a request, check an internal cache, etc.355356```js357import ky from 'ky';358
1026 unmodified lines