Skip to content
Permalink
Browse files

Fix `afterResponse` hook & retry not being called (#95)

  • Loading branch information...
7Pass authored and szmarczak committed Feb 21, 2019
1 parent ffdc62f commit cd33a63b25618606360b78e5bd62149951a5b142
Showing with 55 additions and 38 deletions.
  1. +32 −38 index.js
  2. +23 −0 test/hooks.js
@@ -200,37 +200,35 @@ class Ky {

this._options.headers = headers;

this._response = this._fetch();
const fn = async () => {
let response = await this._fetch();

for (const type of responseTypes) {
const isRetriableMethod = retryMethods.has(this._options.method.toLowerCase());
const fn = async () => {
if (this._retryCount > 0) {
this._response = this._fetch();
}
for (const hook of this._hooks.afterResponse) {
// eslint-disable-next-line no-await-in-loop
const modifiedResponse = await hook(response.clone());

let response = await this._response;
if (modifiedResponse instanceof Response) {
response = modifiedResponse;
}
}

for (const hook of this._hooks.afterResponse) {
// eslint-disable-next-line no-await-in-loop
const modifiedResponse = await hook(response.clone());
if (!response.ok && this._throwHttpErrors) {
throw new HTTPError(response);
}

if (modifiedResponse instanceof Response) {
response = modifiedResponse;
}
}
return response;
};

if (!response.ok && (isRetriableMethod || this._throwHttpErrors)) {
throw new HTTPError(response);
}
const isRetriableMethod = retryMethods.has(this._options.method.toLowerCase());
const result = isRetriableMethod ? this._retry(fn) : fn();

return response.clone()[type]();
for (const type of responseTypes) {
result[type] = async () => {
return (await result).clone()[type]();
};

this._response[type] = isRetriableMethod ? this._retry(fn) : fn;
}

return this._response;
return result;
}

_calculateRetryDelay(error) {
@@ -266,24 +264,20 @@ class Ky {
return 0;
}

_retry(fn) {
const retry = async () => {
try {
return await fn();
} catch (error) {
const ms = this._calculateRetryDelay(error);
if (ms !== 0) {
await delay(ms);
return retry();
}

if (this._throwHttpErrors) {
throw error;
}
async _retry(fn) {
try {
return await fn();
} catch (error) {
const ms = this._calculateRetryDelay(error);
if (ms !== 0 && this._retryCount > 0) {
await delay(ms);
return this._retry(fn);
}
};

return retry;
if (this._throwHttpErrors) {
throw error;
}
}
}

async _fetch() {
@@ -222,3 +222,26 @@ test('afterResponse hook can throw error to reject the request promise', async t

await server.close();
});

test('`afterResponse` hook gets called even if using body shortcuts', async t => {
const server = await createTestServer();
server.get('/', (request, response) => {
response.json({});
});

let called = false;
await ky.get(server.url, {
hooks: {
afterResponse: [
response => {
called = true;
return response;
}
]
}
}).json();

t.true(called);

await server.close();
});

0 comments on commit cd33a63

Please sign in to comment.
You can’t perform that action at this time.