-
Notifications
You must be signed in to change notification settings - Fork 8.3k
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
Changes from all commits
df4219a
b7ef503
1142d49
7aa141c
ce59002
98d2e01
5fb330e
cf73ce0
b5895eb
c19489c
9ea7d5c
8155cd8
05ba2b7
d9dc80e
5a35aa9
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -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, {}); | ||
|
@@ -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, | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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); | ||
|
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, | ||
}; | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -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'; | ||
|
@@ -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, | ||
|
@@ -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, | ||
|
@@ -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
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. So if I understand correctly, this new There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Yes, exactly |
||
) => { | ||
const routeSchemas = routeSchemasFromRouteConfig(route, method); | ||
|
||
|
@@ -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, | ||
}); | ||
}; | ||
|
||
|
@@ -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]; | ||
} | ||
|
||
|
There was a problem hiding this comment.
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