Skip to content

Commit 95c20aa

Browse files
committed
Update /api/workplace_search/overview endpoint to use new request handler
1 parent ffb659f commit 95c20aa

File tree

2 files changed

+30
-129
lines changed

2 files changed

+30
-129
lines changed

x-pack/plugins/enterprise_search/server/routes/workplace_search/overview.test.ts

Lines changed: 22 additions & 98 deletions
Original file line numberDiff line numberDiff line change
@@ -4,127 +4,51 @@
44
* you may not use this file except in compliance with the Elastic License.
55
*/
66

7-
import { MockRouter, mockConfig, mockLogger } from '../../__mocks__';
7+
import { MockRouter, mockRequestHandler, mockDependencies } from '../../__mocks__';
88

99
import { registerWSOverviewRoute } from './overview';
1010

11-
jest.mock('node-fetch');
12-
const fetch = jest.requireActual('node-fetch');
13-
const { Response } = fetch;
14-
// eslint-disable-next-line @typescript-eslint/no-var-requires
15-
const fetchMock = require('node-fetch') as jest.Mocked<typeof fetch>;
16-
17-
const ORG_ROUTE = 'http://localhost:3002/ws/org';
18-
19-
describe('engine routes', () => {
11+
describe('Overview route', () => {
2012
describe('GET /api/workplace_search/overview', () => {
21-
const AUTH_HEADER = 'Basic 123';
22-
const mockRequest = {
23-
headers: {
24-
authorization: AUTH_HEADER,
25-
},
26-
query: {},
27-
};
28-
29-
const mockRouter = new MockRouter({ method: 'get', payload: 'query' });
13+
let mockRouter: MockRouter;
3014

3115
beforeEach(() => {
3216
jest.clearAllMocks();
33-
mockRouter.createRouter();
17+
mockRouter = new MockRouter({ method: 'get', payload: 'query' });
3418

3519
registerWSOverviewRoute({
20+
...mockDependencies,
3621
router: mockRouter.router,
37-
log: mockLogger,
38-
config: mockConfig,
3922
});
4023
});
4124

42-
describe('when the underlying Workplace Search API returns a 200', () => {
43-
beforeEach(() => {
44-
WorkplaceSearchAPI.shouldBeCalledWith(ORG_ROUTE, {
45-
headers: { Authorization: AUTH_HEADER },
46-
}).andReturn({ accountsCount: 1 });
47-
});
48-
49-
it('should return 200 with a list of overview from the Workplace Search API', async () => {
50-
await mockRouter.callRoute(mockRequest);
51-
52-
expect(mockRouter.response.ok).toHaveBeenCalledWith({
53-
body: { accountsCount: 1 },
54-
headers: { 'content-type': 'application/json' },
55-
});
25+
it('creates a request handler', () => {
26+
expect(mockRequestHandler.createRequest).toHaveBeenCalledWith({
27+
path: '/ws/org',
28+
hasValidData: expect.any(Function),
5629
});
5730
});
5831

59-
describe('when the Workplace Search URL is invalid', () => {
60-
beforeEach(() => {
61-
WorkplaceSearchAPI.shouldBeCalledWith(ORG_ROUTE, {
62-
headers: { Authorization: AUTH_HEADER },
63-
}).andReturnError();
64-
});
32+
describe('hasValidData', () => {
33+
it('should correctly validate that the response has data', () => {
34+
const response = {
35+
accountsCount: 1,
36+
};
6537

66-
it('should return 502 with a message', async () => {
67-
await mockRouter.callRoute(mockRequest);
38+
const { hasValidData } = mockRequestHandler.createRequest.mock.calls[0][0];
6839

69-
expect(mockRouter.response.customError).toHaveBeenCalledWith({
70-
statusCode: 502,
71-
body: 'cannot-connect',
72-
});
73-
expect(mockLogger.error).toHaveBeenCalledWith('Cannot connect to Workplace Search: Failed');
74-
expect(mockLogger.debug).not.toHaveBeenCalled();
40+
expect(hasValidData(response)).toBe(true);
7541
});
76-
});
7742

78-
describe('when the Workplace Search API returns invalid data', () => {
79-
beforeEach(() => {
80-
WorkplaceSearchAPI.shouldBeCalledWith(ORG_ROUTE, {
81-
headers: { Authorization: AUTH_HEADER },
82-
}).andReturnInvalidData();
83-
});
43+
it('should correctly validate that a response does not have data', () => {
44+
const response = {
45+
foo: 'bar',
46+
};
8447

85-
it('should return 502 with a message', async () => {
86-
await mockRouter.callRoute(mockRequest);
48+
const hasValidData = mockRequestHandler.createRequest.mock.calls[0][0].hasValidData;
8749

88-
expect(mockRouter.response.customError).toHaveBeenCalledWith({
89-
statusCode: 502,
90-
body: 'cannot-connect',
91-
});
92-
expect(mockLogger.error).toHaveBeenCalledWith(
93-
'Cannot connect to Workplace Search: Error: Invalid data received from Workplace Search: {"foo":"bar"}'
94-
);
95-
expect(mockLogger.debug).toHaveBeenCalled();
50+
expect(hasValidData(response)).toBe(false);
9651
});
9752
});
98-
99-
const WorkplaceSearchAPI = {
100-
shouldBeCalledWith(expectedUrl: string, expectedParams: object) {
101-
return {
102-
andReturn(response: object) {
103-
fetchMock.mockImplementation((url: string, params: object) => {
104-
expect(url).toEqual(expectedUrl);
105-
expect(params).toEqual(expectedParams);
106-
107-
return Promise.resolve(new Response(JSON.stringify(response)));
108-
});
109-
},
110-
andReturnInvalidData() {
111-
fetchMock.mockImplementation((url: string, params: object) => {
112-
expect(url).toEqual(expectedUrl);
113-
expect(params).toEqual(expectedParams);
114-
115-
return Promise.resolve(new Response(JSON.stringify({ foo: 'bar' })));
116-
});
117-
},
118-
andReturnError() {
119-
fetchMock.mockImplementation((url: string, params: object) => {
120-
expect(url).toEqual(expectedUrl);
121-
expect(params).toEqual(expectedParams);
122-
123-
return Promise.reject('Failed');
124-
});
125-
},
126-
};
127-
},
128-
};
12953
});
13054
});

x-pack/plugins/enterprise_search/server/routes/workplace_search/overview.ts

Lines changed: 8 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -4,43 +4,20 @@
44
* you may not use this file except in compliance with the Elastic License.
55
*/
66

7-
import fetch from 'node-fetch';
8-
97
import { IRouteDependencies } from '../../plugin';
108

11-
export function registerWSOverviewRoute({ router, config, log }: IRouteDependencies) {
9+
export function registerWSOverviewRoute({
10+
router,
11+
enterpriseSearchRequestHandler,
12+
}: IRouteDependencies) {
1213
router.get(
1314
{
1415
path: '/api/workplace_search/overview',
1516
validate: false,
1617
},
17-
async (context, request, response) => {
18-
try {
19-
const entSearchUrl = config.host as string;
20-
const url = `${encodeURI(entSearchUrl)}/ws/org`;
21-
22-
const overviewResponse = await fetch(url, {
23-
headers: { Authorization: request.headers.authorization as string },
24-
});
25-
26-
const body = await overviewResponse.json();
27-
const hasValidData = typeof body?.accountsCount === 'number';
28-
29-
if (hasValidData) {
30-
return response.ok({
31-
body,
32-
headers: { 'content-type': 'application/json' },
33-
});
34-
} else {
35-
// Either a completely incorrect Enterprise Search host URL was configured, or Workplace Search is returning bad data
36-
throw new Error(`Invalid data received from Workplace Search: ${JSON.stringify(body)}`);
37-
}
38-
} catch (e) {
39-
log.error(`Cannot connect to Workplace Search: ${e.toString()}`);
40-
if (e instanceof Error) log.debug(e.stack as string);
41-
42-
return response.customError({ statusCode: 502, body: 'cannot-connect' });
43-
}
44-
}
18+
enterpriseSearchRequestHandler.createRequest({
19+
path: '/ws/org',
20+
hasValidData: (body: { accountsCount: number }) => typeof body?.accountsCount === 'number',
21+
})
4522
);
4623
}

0 commit comments

Comments
 (0)