Skip to content

Commit

Permalink
Add support for GET requests
Browse files Browse the repository at this point in the history
  • Loading branch information
madirey committed Feb 2, 2020
1 parent 47d0e0d commit fc443b6
Show file tree
Hide file tree
Showing 3 changed files with 86 additions and 21 deletions.
40 changes: 39 additions & 1 deletion x-pack/plugins/endpoint/server/routes/alerts.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -109,8 +109,9 @@ describe('test alerts route', () => {
expect(alertResultList.request_page_size).toEqual(10);
});

it('should return alert results according to pagination params', async () => {
it('should return alert results according to pagination params -- POST', async () => {
const mockRequest = httpServerMock.createKibanaRequest({
method: 'post',
body: {
paging_properties: [
{
Expand Down Expand Up @@ -150,4 +151,41 @@ describe('test alerts route', () => {
expect(alertResultList.request_page_index).toEqual(40);
expect(alertResultList.request_page_size).toEqual(20);
});

it('should return alert results according to pagination params -- GET', async () => {
const mockRequest = httpServerMock.createKibanaRequest({
path: '/api/endpoint/alerts?page_size=20&page_index=2',
query: {
page_size: 20,
page_index: 2,
},
});
mockScopedClient.callAsCurrentUser.mockImplementationOnce(() =>
Promise.resolve((data as unknown) as SearchResponse<AlertData>)
);
[routeConfig, routeHandler] = routerMock.get.mock.calls.find(([{ path }]) =>
path.startsWith('/api/endpoint/alerts')
)!;

await routeHandler(
({
core: {
elasticsearch: {
dataClient: mockScopedClient,
},
},
} as unknown) as RequestHandlerContext,
mockRequest,
mockResponse
);

expect(mockScopedClient.callAsCurrentUser).toBeCalled();
expect(routeConfig.options).toEqual({ authRequired: true });
expect(mockResponse.ok).toBeCalled();
const alertResultList = mockResponse.ok.mock.calls[0][0]?.body as AlertResultList;
expect(alertResultList.alerts.length).toEqual(20);
expect(alertResultList.total).toEqual(132);
expect(alertResultList.request_page_index).toEqual(40);
expect(alertResultList.request_page_size).toEqual(20);
});
});
40 changes: 27 additions & 13 deletions x-pack/plugins/endpoint/server/routes/alerts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,17 +5,42 @@
*/

import { IRouter } from 'kibana/server';
import { RequestHandler } from 'kibana/server';
import { SearchResponse } from 'elasticsearch';
import { schema } from '@kbn/config-schema';

import { kibanaRequestToAlertListQuery } from '../services/endpoint/alert_query_builders';
import { AlertData, AlertResultList } from '../../common/types';
import { EndpointAppContext } from '../types';

const ALERTS_ROUTE = '/api/endpoint/alerts';

export function registerAlertRoutes(router: IRouter, endpointAppContext: EndpointAppContext) {
const alertsHandler: RequestHandler<any, any, any> = async (ctx, req, res) => {
try {
const queryParams = await kibanaRequestToAlertListQuery(req, endpointAppContext);
const response = (await ctx.core.elasticsearch.dataClient.callAsCurrentUser(
'search',
queryParams
)) as SearchResponse<AlertData>;
return res.ok({ body: mapToAlertResultList(queryParams, response) });
} catch (err) {
return res.internalError({ body: err });
}
};

router.get(
{
path: ALERTS_ROUTE,
validate: {},
options: { authRequired: true },
},
alertsHandler
);

router.post(
{
path: '/api/endpoint/alerts',
path: ALERTS_ROUTE,
validate: {
body: schema.nullable(
schema.object({
Expand All @@ -38,18 +63,7 @@ export function registerAlertRoutes(router: IRouter, endpointAppContext: Endpoin
},
options: { authRequired: true },
},
async (context, req, res) => {
try {
const queryParams = await kibanaRequestToAlertListQuery(req, endpointAppContext);
const response = (await context.core.elasticsearch.dataClient.callAsCurrentUser(
'search',
queryParams
)) as SearchResponse<AlertData>;
return res.ok({ body: mapToAlertResultList(queryParams, response) });
} catch (err) {
return res.internalError({ body: err });
}
}
alertsHandler
);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/
import qs from 'querystring';
import { KibanaRequest } from 'kibana/server';
import { EndpointAppConstants } from '../../../common/types';
import { EndpointAppContext } from '../../types';
Expand Down Expand Up @@ -36,15 +37,27 @@ async function getPagingProperties(
endpointAppContext: EndpointAppContext
) {
const config = await endpointAppContext.config();
const pagingProperties: { page_size?: number; page_index?: number } = {};
if (request?.body?.paging_properties) {
for (const property of request.body.paging_properties) {
Object.assign(
pagingProperties,
...Object.keys(property).map(key => ({ [key]: property[key] }))
);
let pagingProperties: { page_size?: number; page_index?: number } = {};

if (request?.route?.method === 'get') {
if (typeof request?.url?.query === 'string') {
const qp = qs.parse(request.url.query);
pagingProperties.page_size = Number(qp.page_size);
pagingProperties.page_index = Number(qp.page_index);
} else if (request?.url?.query) {
pagingProperties = request.url.query;
}
} else {
if (request?.body?.paging_properties) {
for (const property of request.body.paging_properties) {
Object.assign(
pagingProperties,
...Object.keys(property).map(key => ({ [key]: property[key] }))
);
}
}
}

return {
pageSize: pagingProperties.page_size || config.alertResultListDefaultPageSize,
pageIndex: pagingProperties.page_index || config.alertResultListDefaultFirstPageIndex,
Expand Down

0 comments on commit fc443b6

Please sign in to comment.