Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[HTTP/OAS] Prepare router and versioned router for generating OAS #180275

Merged
merged 15 commits into from
Apr 11, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions packages/core/http/core-http-router-server-internal/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
*/

export { filterHeaders } from './src/headers';
export { versionHandlerResolvers } from './src/versioned_router';
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not used in this PR, just exporting in preparation for future PR, happy to hold off on this change

export { CoreVersionedRouter } from './src/versioned_router';
export { Router, type RouterOptions } from './src/router';
export type { HandlerResolutionStrategy } from './src/versioned_router';
export { isKibanaRequest, isRealRequest, ensureRawRequest, CoreKibanaRequest } from './src/request';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,16 @@
import { Router, type RouterOptions } from './router';
import { loggingSystemMock } from '@kbn/core-logging-server-mocks';
import { schema } from '@kbn/config-schema';
import { createFooValidation } from './router.test.util';
import { createRequestMock } from '@kbn/hapi-mocks/src/request';

const mockResponse: any = {
code: jest.fn().mockImplementation(() => mockResponse),
header: jest.fn().mockImplementation(() => mockResponse),
};
const mockResponseToolkit: any = {
response: jest.fn().mockReturnValue(mockResponse),
};

const logger = loggingSystemMock.create().get();
const enhanceWithContext = (fn: (...args: any[]) => any) => fn.bind(null, {});
Expand All @@ -22,6 +32,85 @@ const routerOptions: RouterOptions = {
};

describe('Router', () => {
afterEach(() => jest.clearAllMocks());
describe('#getRoutes', () => {
it('returns expected route metadata', () => {
const router = new Router('', logger, enhanceWithContext, routerOptions);
const validation = schema.object({ foo: schema.string() });
router.post(
{ path: '/', validate: { body: validation, query: validation, params: validation } },
(context, req, res) => res.ok()
);
const routes = router.getRoutes();
expect(routes).toHaveLength(1);
const [route] = routes;
expect(route).toMatchObject({
handler: expect.any(Function),
method: 'post',
path: '/',
validationSchemas: { body: validation, query: validation, params: validation },
isVersioned: false,
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Mainly making sure that the above two fields are included as expected, will be used by OAS generation script

});
});

it('can exclude versioned routes', () => {
const router = new Router('', logger, enhanceWithContext, routerOptions);
const validation = schema.object({ foo: schema.string() });
router.post(
{
path: '/versioned',
validate: { body: validation, query: validation, params: validation },
},
(context, req, res) => res.ok(),
{ isVersioned: true }
);
router.get(
{
path: '/unversioned',
validate: { body: validation, query: validation, params: validation },
},
(context, req, res) => res.ok()
);
const routes = router.getRoutes({ excludeVersionedRoutes: true });
expect(routes).toHaveLength(1);
const [route] = routes;
expect(route).toMatchObject({
method: 'get',
path: '/unversioned',
});
});
});

const { fooValidation, validateBodyFn, validateOutputFn, validateParamsFn, validateQueryFn } =
createFooValidation();

it.each([['static' as const], ['lazy' as const]])(
'runs %s route validations',
async (staticOrLazy) => {
const router = new Router('', logger, enhanceWithContext, routerOptions);
router.post(
{
path: '/',
validate: staticOrLazy ? fooValidation : () => fooValidation,
},
(context, req, res) => res.ok()
);
const [{ handler }] = router.getRoutes();
await handler(
createRequestMock({
params: { foo: 1 },
query: { foo: 1 },
payload: { foo: 1 },
}),
mockResponseToolkit
);
expect(validateBodyFn).toHaveBeenCalledTimes(1);
expect(validateParamsFn).toHaveBeenCalledTimes(1);
expect(validateQueryFn).toHaveBeenCalledTimes(1);
expect(validateOutputFn).toHaveBeenCalledTimes(0);
}
);

describe('Options', () => {
it('throws if validation for a route is not defined explicitly', () => {
const router = new Router('', logger, enhanceWithContext, routerOptions);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/

import { schema } from '@kbn/config-schema';

export function createFooValidation() {
const validateBodyFn = jest.fn();
const validateParamsFn = jest.fn();
const validateQueryFn = jest.fn();
const validateOutputFn = jest.fn();
const fooValidation = {
request: {
body: schema.object({
foo: schema.number({
validate: validateBodyFn,
}),
}),
params: schema.object({
foo: schema.number({
validate: validateParamsFn,
}),
}),
query: schema.object({
foo: schema.number({
validate: validateQueryFn,
}),
}),
},
response: {
200: {
body: schema.object({
foo: schema.number({
validate: validateOutputFn,
}),
}),
},
},
};

return {
fooValidation,
validateBodyFn,
validateParamsFn,
validateQueryFn,
validateOutputFn,
};
}
47 changes: 39 additions & 8 deletions packages/core/http/core-http-router-server-internal/src/router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import type {
IRouter,
RequestHandler,
VersionedRouter,
RouteRegistrar,
} from '@kbn/core-http-server';
import { validBodyOutput, getRequestValidation } from '@kbn/core-http-server';
import { RouteValidator } from './validator';
Expand All @@ -32,6 +33,7 @@ import { CoreKibanaRequest } from './request';
import { kibanaResponseFactory } from './response';
import { HapiResponseAdapter } from './response_adapter';
import { wrapErrors } from './error_wrapper';
import { Method } from './versioned_router/types';

export type ContextEnhancer<
P,
Expand Down Expand Up @@ -131,18 +133,40 @@ export interface RouterOptions {
};
}

/** @internal */
interface InternalRegistrarOptions {
isVersioned: boolean;
}

/** @internal */
type InternalRegistrar<M extends Method, C extends RequestHandlerContextBase> = <P, Q, B>(
route: RouteConfig<P, Q, B, M>,
handler: RequestHandler<P, Q, B, C, M>,
internalOpts?: InternalRegistrarOptions
) => ReturnType<RouteRegistrar<M, C>>;

/** @internal */
interface InternalRouterRoute extends RouterRoute {
readonly isVersioned: boolean;
}

/** @internal */
interface InternalGetRoutesOptions {
excludeVersionedRoutes?: boolean;
}

/**
* @internal
*/
export class Router<Context extends RequestHandlerContextBase = RequestHandlerContextBase>
implements IRouter<Context>
{
public routes: Array<Readonly<RouterRoute>> = [];
public get: IRouter<Context>['get'];
public post: IRouter<Context>['post'];
public delete: IRouter<Context>['delete'];
public put: IRouter<Context>['put'];
public patch: IRouter<Context>['patch'];
public routes: Array<Readonly<InternalRouterRoute>> = [];
public get: InternalRegistrar<'get', Context>;
public post: InternalRegistrar<'post', Context>;
public delete: InternalRegistrar<'delete', Context>;
public put: InternalRegistrar<'put', Context>;
public patch: InternalRegistrar<'patch', Context>;

constructor(
public readonly routerPath: string,
Expand All @@ -154,7 +178,8 @@ export class Router<Context extends RequestHandlerContextBase = RequestHandlerCo
<Method extends RouteMethod>(method: Method) =>
<P, Q, B>(
route: RouteConfig<P, Q, B, Method>,
handler: RequestHandler<P, Q, B, Context, Method>
handler: RequestHandler<P, Q, B, Context, Method>,
internalOptions: { isVersioned: boolean } = { isVersioned: false }
Comment on lines +181 to +182
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So if I understand correctly, this new internalOptions third parameter doesn't leak on the public interface because we only specify it on the implementation via this new InternalRegistrar type on our method helpers than extends IRouter, is that correct?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, exactly

) => {
const routeSchemas = routeSchemasFromRouteConfig(route, method);

Expand All @@ -169,6 +194,9 @@ export class Router<Context extends RequestHandlerContextBase = RequestHandlerCo
method,
path: getRouteFullPath(this.routerPath, route.path),
options: validOptions(method, route),
/** Below is added for introspection */
validationSchemas: route.validate,
isVersioned: internalOptions.isVersioned,
});
};

Expand All @@ -179,7 +207,10 @@ export class Router<Context extends RequestHandlerContextBase = RequestHandlerCo
this.patch = buildMethod('patch');
}

public getRoutes() {
public getRoutes({ excludeVersionedRoutes }: InternalGetRoutesOptions = {}) {
if (excludeVersionedRoutes) {
return this.routes.filter((route) => !route.isVersioned);
}
return [...this.routes];
}

Expand Down
Loading