Skip to content

Commit

Permalink
Move a REST endpoint and the GQL endpoint to NP routing.
Browse files Browse the repository at this point in the history
  • Loading branch information
justinkambic committed Nov 19, 2019
1 parent b354e7d commit 388b3a7
Show file tree
Hide file tree
Showing 7 changed files with 124 additions and 76 deletions.
2 changes: 1 addition & 1 deletion x-pack/legacy/plugins/uptime/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ export const uptime = (kibana: any) =>
const { elasticsearch, xpack_main } = server.plugins;
plugin(initializerContext).setup(
{
route: (arg: any) => server.route(arg),
route: server.newPlatform.setup.core.http.createRouter(),
},
{
elasticsearch,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@ import { GraphQLOptions } from 'apollo-server-core';
import { GraphQLSchema } from 'graphql';
import { Lifecycle, ResponseToolkit } from 'hapi';
import { RouteOptions } from 'hapi';
import { SavedObjectsLegacyService } from 'src/core/server';
import { SavedObjectsLegacyService, RequestHandler, IRouter } from 'src/core/server';
import { ObjectType } from '@kbn/config-schema';

export interface UMFrameworkRequest {
user: string;
Expand All @@ -21,17 +22,19 @@ export interface UMFrameworkRequest {
export type UMFrameworkResponse = Lifecycle.ReturnValue;

export interface UMFrameworkRouteOptions<
RouteRequest extends UMFrameworkRequest,
RouteResponse extends UMFrameworkResponse
P extends ObjectType,
Q extends ObjectType,
B extends ObjectType
> {
path: string;
method: string;
handler: (req: Request, h: ResponseToolkit) => any;
handler: RequestHandler<P, Q, B>;
config?: any;
validate: any;
}

export interface UptimeCoreSetup {
route: any;
route: IRouter;
}

export interface UptimeCorePlugins {
Expand All @@ -57,7 +60,7 @@ export interface UMHapiGraphQLPluginOptions {

export interface UMBackendFrameworkAdapter {
registerRoute<RouteRequest extends UMFrameworkRequest, RouteResponse extends UMFrameworkResponse>(
route: UMFrameworkRouteOptions<RouteRequest, RouteResponse>
route: UMFrameworkRouteOptions<ObjectType, ObjectType, ObjectType>
): void;
registerGraphQLEndpoint(routePath: string, schema: GraphQLSchema): void;
getSavedObjectsClient(): any;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,16 @@
*/

import { GraphQLSchema } from 'graphql';
import { Request, ResponseToolkit } from 'hapi';
import { schema as kbnSchema } from '@kbn/config-schema';
import { runHttpQuery } from 'apollo-server-core';
import { ObjectType } from '@kbn/config-schema';
import { UptimeCorePlugins, UptimeCoreSetup } from './adapter_types';
import {
UMBackendFrameworkAdapter,
UMFrameworkRequest,
UMFrameworkResponse,
UMFrameworkRouteOptions,
} from './adapter_types';
import { DEFAULT_GRAPHQL_PATH } from '../../../graphql';

export class UMKibanaBackendFrameworkAdapter implements UMBackendFrameworkAdapter {
constructor(
Expand All @@ -28,8 +28,25 @@ export class UMKibanaBackendFrameworkAdapter implements UMBackendFrameworkAdapte
public registerRoute<
RouteRequest extends UMFrameworkRequest,
RouteResponse extends UMFrameworkResponse
>(route: UMFrameworkRouteOptions<RouteRequest, RouteResponse>) {
this.server.route(route);
>({
handler,
method,
path,
validate,
}: UMFrameworkRouteOptions<ObjectType, ObjectType, ObjectType>) {
switch (method) {
case 'GET':
this.server.route.get(
{
path,
validate,
},
handler
);
break;
default:
throw new Error(`Handler for method ${method} is not defined`);
}
}

public registerGraphQLEndpoint(routePath: string, schema: GraphQLSchema): void {
Expand All @@ -43,37 +60,44 @@ export class UMKibanaBackendFrameworkAdapter implements UMBackendFrameworkAdapte
tags: ['access:uptime'],
},
};
this.server.route({
options: options.route,
handler: async (request: Request, h: ResponseToolkit) => {
this.server.route.post(
{
path: routePath,
validate: {
body: kbnSchema.object({
operationName: kbnSchema.string(),
query: kbnSchema.string(),
variables: kbnSchema.recordOf(kbnSchema.string(), kbnSchema.any()),
}),
},
},
async (context, request, resp): Promise<any> => {
try {
const { method } = request;
const query =
method === 'post'
? (request.payload as Record<string, any>)
: (request.query as Record<string, any>);
const query = request.body as Record<string, any>;

const graphQLResponse = await runHttpQuery([request], {
method: method.toUpperCase(),
method: 'POST',
options: options.graphQLOptions,
query,
});

return h.response(graphQLResponse).type('application/json');
return resp.ok({
body: graphQLResponse,
headers: {
'content-type': 'application/json',
},
});
} catch (error) {
if (error.isGraphQLError === true) {
return h
.response(error.message)
.code(error.statusCode)
.type('application/json');
return resp.internalError({
body: { message: error.message },
headers: { 'content-type': 'application/json' },
});
}
return h.response(error).type('application/json');
return resp.internalError();
}
},
method: ['get', 'post'],
path: options.path || DEFAULT_GRAPHQL_PATH,
vhost: undefined,
});
}
);
}

public getSavedObjectsClient() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
* you may not use this file except in compliance with the Elastic License.
*/

import Boom from 'boom';
import { UMServerLibs } from '../lib/lib';
import { UMRestApiRouteCreator, UMServerRoute } from './types';

Expand All @@ -13,17 +12,18 @@ export const createRouteWithAuth = (
routeCreator: UMRestApiRouteCreator
): UMServerRoute => {
const restRoute = routeCreator(libs);
const { handler, method, path, options } = restRoute;
const authHandler = async (request: any, h: any) => {
if (libs.auth.requestIsValid(request)) {
return await handler(request, h);
}
return Boom.badRequest();
};
const { handler, method, path, options, ...rest } = restRoute;
// const authHandler = async (request: any, h: any) => {
// if (libs.auth.requestIsValid(request)) {
// return await handler(request, h);
// }
// return Boom.badRequest();
// };
return {
method,
path,
options,
handler: authHandler,
handler, // : authHandler,
...rest,
};
};
14 changes: 7 additions & 7 deletions x-pack/legacy/plugins/uptime/server/rest_api/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,18 +4,18 @@
* you may not use this file except in compliance with the Elastic License.
*/

import { createIsValidRoute } from './auth';
// import { createIsValidRoute } from './auth';
import { createGetAllRoute } from './pings';
import { createGetIndexPatternRoute } from './index_pattern';
import { createLogMonitorPageRoute, createLogOverviewPageRoute } from './telemetry';
// import { createGetIndexPatternRoute } from './index_pattern';
// import { createLogMonitorPageRoute, createLogOverviewPageRoute } from './telemetry';
import { UMRestApiRouteCreator } from './types';

export * from './types';
export { createRouteWithAuth } from './create_route_with_auth';
export const restApiRoutes: UMRestApiRouteCreator[] = [
createIsValidRoute,
// //createIsValidRoute,
createGetAllRoute,
createLogMonitorPageRoute,
createLogOverviewPageRoute,
createGetIndexPatternRoute,
// //createLogMonitorPageRoute,
// //createLogOverviewPageRoute,
// //createGetIndexPatternRoute,
];
75 changes: 47 additions & 28 deletions x-pack/legacy/plugins/uptime/server/rest_api/pings/get_all.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,36 +4,55 @@
* you may not use this file except in compliance with the Elastic License.
*/

import Joi from 'joi';
import { PingResults } from '../../../common/graphql/types';
import { schema } from '@kbn/config-schema';
import { UMServerLibs } from '../../lib/lib';
import { UMRestApiRouteCreator } from '../types';

export const createGetAllRoute = (libs: UMServerLibs) => ({
method: 'GET',
path: '/api/uptime/pings',
options: {
export const createGetAllRoute: UMRestApiRouteCreator = (libs: UMServerLibs) => {
return {
method: 'GET',
path: '/api/uptime/pings',
validate: {
query: Joi.object({
dateRangeStart: Joi.number().required(),
dateRangeEnd: Joi.number().required(),
monitorId: Joi.string(),
size: Joi.number(),
sort: Joi.string(),
status: Joi.string(),
query: schema.object({
dateRangeStart: schema.string(),
dateRangeEnd: schema.string(),
location: schema.maybe(schema.string()),
monitorId: schema.maybe(schema.string()),
size: schema.maybe(schema.number()),
sort: schema.maybe(schema.string()),
status: schema.maybe(schema.string()),
}),
},
tags: ['access:uptime'],
},
handler: async (request: any): Promise<PingResults> => {
const { size, sort, dateRangeStart, dateRangeEnd, monitorId, status } = request.query;
return await libs.pings.getAll(
request,
dateRangeStart,
dateRangeEnd,
monitorId,
status,
sort,
size
);
},
});
options: {
tags: ['access:uptime'],
},
handler: async (context, request, resp): Promise<any> => {
const {
size,
sort,
dateRangeStart,
dateRangeEnd,
location,
monitorId,
status,
} = request.query;

const result = await libs.pings.getAll(
request,
dateRangeStart,
dateRangeEnd,
monitorId,
status,
sort,
size,
location
);

return resp.ok({
body: {
...result,
},
});
},
};
};
4 changes: 3 additions & 1 deletion x-pack/legacy/plugins/uptime/server/rest_api/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,15 @@
* you may not use this file except in compliance with the Elastic License.
*/

import { ObjectType } from '@kbn/config-schema';
import { RequestHandler } from 'kibana/server';
import { UMServerLibs } from '../lib/lib';

export interface UMServerRoute {
method: string;
path: string;
options?: any;
handler: (request: any, h?: any) => any;
handler: RequestHandler<ObjectType, ObjectType, ObjectType>;
}

export type UMRestApiRouteCreator = (libs: UMServerLibs) => UMServerRoute;

0 comments on commit 388b3a7

Please sign in to comment.