Skip to content

Commit

Permalink
Allow returning Response from a beforeRequest hook (#172)
Browse files Browse the repository at this point in the history
  • Loading branch information
hugomrdias authored and szmarczak committed Sep 9, 2019
1 parent ac07244 commit 59d36ac
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 1 deletion.
6 changes: 5 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -414,7 +414,11 @@ class Ky {
async _fetch() {
for (const hook of this._hooks.beforeRequest) {
// eslint-disable-next-line no-await-in-loop
await hook(this._input, this._options);
const result = await hook(this._input, this._options);

if (result instanceof Response) {
return result;
}
}

if (this._timeout === false) {
Expand Down
4 changes: 4 additions & 0 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -226,6 +226,10 @@ Default: `[]`

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 normalized input and options as arguments. You could, for example, modify `options.headers` here.

A [Response](https://developer.mozilla.org/en-US/docs/Web/API/Response) instance can be returned from a `beforeRequest` hook to completely avoid making an HTTP request. This is very helpful when mocking a request or using an internal cache.

**Note:** all the following hooks will be skipped.

Note that the argument order has changed in non-backward compatible way since [#163](https://github.com/sindresorhus/ky/pull/163).

###### hooks.afterResponse
Expand Down
12 changes: 12 additions & 0 deletions test/hooks.js
Original file line number Diff line number Diff line change
Expand Up @@ -291,3 +291,15 @@ test.failing('`afterResponse` hook is called with input, normalized options, and

await server.close();
});

test('hooks beforeRequest returning Response skips HTTP Request', async t => {
const expectedResponse = 'empty hook';

const response = await ky.get('server.url', {hooks: {
beforeRequest: [
() => new Response(expectedResponse, {status: 200, statusText: 'OK'})
]
}}).text();

t.is(response, expectedResponse);
});

0 comments on commit 59d36ac

Please sign in to comment.