Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow returning Response from a beforeRequest hook #172

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -383,7 +383,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);
});