Skip to content

Commit

Permalink
Go back to using promises (which still return abort method) and updat…
Browse files Browse the repository at this point in the history
…e test
  • Loading branch information
lukasolson committed Jun 12, 2019
1 parent 4427234 commit 40cfb39
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 9 deletions.
14 changes: 11 additions & 3 deletions src/core/server/elasticsearch/cluster_client.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -165,15 +165,23 @@ describe('#callAsInternalUser', () => {
).rejects.toStrictEqual(mockAuthenticationError);
});

test('sets the onabort property of a signal if provided', () => {
test('aborts the request and rejects if a signal is provided and aborted', async () => {
const controller = new AbortController();

clusterClient.callAsInternalUser('ping', undefined, {
// The ES client returns a promise with an additional `abort` method to abort the request
const mockValue: any = Promise.resolve();
mockValue.abort = jest.fn();
mockEsClientInstance.ping.mockReturnValue(mockValue);

const promise = clusterClient.callAsInternalUser('ping', undefined, {
wrap401Errors: false,
signal: controller.signal,
});

expect(typeof controller.signal.onabort).toBe('function');
controller.abort();

expect(mockValue.abort).toHaveBeenCalled();
await expect(promise).rejects.toThrowErrorMatchingInlineSnapshot(`"Request was aborted"`);
});

test('does not override WWW-Authenticate if returned by Elasticsearch', async () => {
Expand Down
12 changes: 6 additions & 6 deletions src/core/server/elasticsearch/cluster_client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,14 +71,14 @@ async function callAPI(
const apiContext = clientPath.length === 1 ? client : get(client, clientPath.slice(0, -1));
try {
return await new Promise((resolve, reject) => {
// We have to use a callback here instead of using promises directly because it's the only way
// to get access to the abort method on the request
const request = api.call(apiContext, clientParams, (err: any, res: any) =>
err ? reject(err) : resolve(res)
);
const request = api.call(apiContext, clientParams);
if (options.signal) {
options.signal.onabort = () => request.abort();
options.signal.addEventListener('abort', () => {
request.abort();
reject(new Error('Request was aborted'));
});
}
return request.then(resolve, reject);
});
} catch (err) {
if (!options.wrap401Errors || err.statusCode !== 401) {
Expand Down

0 comments on commit 40cfb39

Please sign in to comment.