Skip to content

Commit

Permalink
Rename responseInterceptors -> responseHnadlers. Add comment to inter…
Browse files Browse the repository at this point in the history
…face.
  • Loading branch information
cjcenizal committed Oct 6, 2021
1 parent b74c685 commit 7ff8d58
Show file tree
Hide file tree
Showing 5 changed files with 33 additions and 32 deletions.
2 changes: 1 addition & 1 deletion src/plugins/es_ui_shared/public/request/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,6 @@ export {
SendRequestConfig,
SendRequestResponse,
sendRequest,
ResponseInterceptor,
ResponseHandler,
} from './send_request';
export { UseRequestConfig, UseRequestResponse, useRequest } from './use_request';
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,11 @@ import {
export interface SendRequestHelpers {
getSendRequestSpy: () => sinon.SinonStub;
sendSuccessRequest: (
responseInterceptors?: SendRequestConfig['responseInterceptors']
responseHandlers?: SendRequestConfig['responseHandlers']
) => Promise<SendRequestResponse>;
getSuccessResponse: () => SendRequestResponse;
sendErrorRequest: (
responseInterceptors?: SendRequestConfig['responseInterceptors']
responseHandlers?: SendRequestConfig['responseHandlers']
) => Promise<SendRequestResponse>;
getErrorResponse: () => SendRequestResponse;
}
Expand Down Expand Up @@ -53,8 +53,8 @@ export const createSendRequestHelpers = (): SendRequestHelpers => {
})
)
.resolves(successResponse);
const sendSuccessRequest = (responseInterceptors?: SendRequestConfig['responseInterceptors']) =>
sendRequest({ ...successRequest, responseInterceptors });
const sendSuccessRequest = (responseHandlers?: SendRequestConfig['responseHandlers']) =>
sendRequest({ ...successRequest, responseHandlers });
const getSuccessResponse = () => ({ data: successResponse.data, error: null });

// Set up failed request helpers.
Expand All @@ -67,8 +67,8 @@ export const createSendRequestHelpers = (): SendRequestHelpers => {
})
)
.rejects(errorResponse);
const sendErrorRequest = (responseInterceptors?: SendRequestConfig['responseInterceptors']) =>
sendRequest({ ...errorRequest, responseInterceptors });
const sendErrorRequest = (responseHandlers?: SendRequestConfig['responseHandlers']) =>
sendRequest({ ...errorRequest, responseHandlers });
const getErrorResponse = () => ({
data: null,
error: errorResponse.response.data,
Expand Down
24 changes: 12 additions & 12 deletions src/plugins/es_ui_shared/public/request/send_request.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,24 +34,24 @@ describe('sendRequest function', () => {
expect(errorResponse).toEqual(getErrorResponse());
});

it('calls responseInterceptors with successful responses', async () => {
it('calls responseHandlers with successful responses', async () => {
const { sendSuccessRequest, getSuccessResponse } = helpers;
const successInterceptorSpy = sinon.spy();
const successInterceptors = [successInterceptorSpy];
const successHandlerSpy = sinon.spy();
const successHandlers = [successHandlerSpy];

await sendSuccessRequest(successInterceptors);
sinon.assert.calledOnce(successInterceptorSpy);
sinon.assert.calledWith(successInterceptorSpy, getSuccessResponse());
await sendSuccessRequest(successHandlers);
sinon.assert.calledOnce(successHandlerSpy);
sinon.assert.calledWith(successHandlerSpy, getSuccessResponse());
});

it('calls responseInterceptors with errors', async () => {
it('calls responseHandlers with errors', async () => {
const { sendErrorRequest, getErrorResponse } = helpers;
const errorInterceptorSpy = sinon.spy();
const errorInterceptors = [errorInterceptorSpy];
const errorHandlerSpy = sinon.spy();
const errorHandlers = [errorHandlerSpy];

// For some reason sinon isn't throwing an error on rejection, as an awaited Promise normally would.
await sendErrorRequest(errorInterceptors);
sinon.assert.calledOnce(errorInterceptorSpy);
sinon.assert.calledWith(errorInterceptorSpy, getErrorResponse());
await sendErrorRequest(errorHandlers);
sinon.assert.calledOnce(errorHandlerSpy);
sinon.assert.calledWith(errorHandlerSpy, getErrorResponse());
});
});
21 changes: 11 additions & 10 deletions src/plugins/es_ui_shared/public/request/send_request.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@

import { HttpSetup, HttpFetchQuery } from '../../../../../src/core/public';

export type ResponseInterceptor = ({ data, error }: { data: any; error: any }) => void;
export type ResponseHandler = ({ data, error }: { data: any; error: any }) => void;

export interface SendRequestConfig {
path: string;
Expand All @@ -20,7 +20,11 @@ export interface SendRequestConfig {
* HttpFetchOptions#asSystemRequest.
*/
asSystemRequest?: boolean;
responseInterceptors?: ResponseInterceptor[];
/**
* Optional handlers for triggering side effects based on a request's
* successful response or errror. These don't mutate responses or errors.
*/
responseHandlers?: ResponseHandler[];
}

export interface SendRequestResponse<D = any, E = any> {
Expand All @@ -30,16 +34,13 @@ export interface SendRequestResponse<D = any, E = any> {

// Pass the response sequentially through each interceptor, allowing for
// side effects to be run.
const updateResponseInterceptors = (
response: any,
responseInterceptors: ResponseInterceptor[] = []
) => {
responseInterceptors.forEach((interceptor) => interceptor(response));
const updateResponseHandlers = (response: any, responseHandlers: ResponseHandler[] = []) => {
responseHandlers.forEach((interceptor) => interceptor(response));
};

export const sendRequest = async <D = any, E = any>(
httpClient: HttpSetup,
{ path, method, body, query, asSystemRequest, responseInterceptors }: SendRequestConfig
{ path, method, body, query, asSystemRequest, responseHandlers }: SendRequestConfig
): Promise<SendRequestResponse<D, E>> => {
try {
const stringifiedBody = typeof body === 'string' ? body : JSON.stringify(body);
Expand All @@ -54,15 +55,15 @@ export const sendRequest = async <D = any, E = any>(
error: null,
};

updateResponseInterceptors(response, responseInterceptors);
updateResponseHandlers(response, responseHandlers);
return response;
} catch (e) {
const response = {
data: null,
error: e.response?.data ?? e.body,
};

updateResponseInterceptors(response, responseInterceptors);
updateResponseHandlers(response, responseHandlers);
return response;
}
};
6 changes: 3 additions & 3 deletions src/plugins/es_ui_shared/public/request/use_request.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ export const useRequest = <D = any, E = Error>(
pollIntervalMs,
initialData,
deserializer,
responseInterceptors,
responseHandlers,
}: UseRequestConfig
): UseRequestResponse<D, E> => {
const isMounted = useRef(false);
Expand Down Expand Up @@ -89,7 +89,7 @@ export const useRequest = <D = any, E = Error>(
// Any requests that are sent in the background (without user interaction) should be flagged as "system requests". This should not be
// confused with any terminology in Elasticsearch. This is a Kibana-specific construct that allows the server to differentiate between
// user-initiated and requests "system"-initiated requests, for purposes like security features.
const requestPayload = { ...requestBody, asSystemRequest, responseInterceptors };
const requestPayload = { ...requestBody, asSystemRequest, responseHandlers };
const response = await sendRequest<D, E>(httpClient, requestPayload);
const { data: serializedResponseData, error: responseError } = response;

Expand All @@ -115,7 +115,7 @@ export const useRequest = <D = any, E = Error>(
// Setting isLoading to false also acts as a signal for scheduling the next poll request.
setIsLoading(false);
},
[requestBody, httpClient, deserializer, clearPollInterval, responseInterceptors]
[requestBody, httpClient, deserializer, clearPollInterval, responseHandlers]
);

const scheduleRequest = useCallback(() => {
Expand Down

0 comments on commit 7ff8d58

Please sign in to comment.