import type { IRouter } from 'src/core/server' ; import { get } from 'lodash' ; import { elasticsearchServiceMock } from '../../../../../../src/core/server/mocks' ; type RequestHandler = ( ... params : any [ ] ) => any ; type RequestMethod = 'get' | 'post' | 'put' | 'delete' | 'patch' ; interface HandlersByUrl { [ key ] : RequestHandler ; } const responseIntercepted = { ok ( response ) { return response ; } , conflict ( response ) { response . status = 409 ; return response ; } , internalError ( response ) { response . status = 500 ; return response ; } , notFound ( response ) { response . status = 404 ; return response ; } , } ; /**
 * Create a proxy with a default "catch all" handler to make sure we don't break route handlers that make use
 * of other method on the response object that the ones defined in `responseIntercepted` above.
 */ const responseMock = new Proxy ( responseIntercepted , { get : ( target , prop ) => ( prop in target ? target [ prop ] : ( response ) => response ) , has : ( ) => true , } ) ; export interface RequestMock { method : RequestMethod ; path : string ; [ key ] : any ; } export class RouterMock implements IRouter { /**
     * Cache to keep a reference to all the request handler defined on the router for each HTTP method and path
     */ private cacheHandlers : { [ key ] : HandlersByUrl ; } = { get : { } , post : { } , put : { } , delete : { } , patch : { } , } ; public contextMock = { core : { elasticsearch : { client : elasticsearchServiceMock . createScopedClusterClient ( ) } } , } ; getRoutes = jest . fn ( ) ; handleLegacyErrors = jest . fn ( ) ; routerPath = '' ; get ( { path } , handler ) { this . cacheHandlers . get [ path ] = handler ; } post ( { path } , handler ) { this . cacheHandlers . post [ path ] = handler ; } put ( { path } , handler ) { this . cacheHandlers . put [ path ] = handler ; } delete ( { path } , handler ) { this . cacheHandlers . delete [ path ] = handler ; } patch ( { path } , handler ) { this . cacheHandlers . patch [ path ] = handler ; } getMockApiFn ( path ) { return get ( this . contextMock . core . elasticsearch . client . asCurrentUser , path ) ; } runRequest ( { method , path , ... mockRequest } ) { const handler = this . cacheHandlers [ method ] [ path ] ; if ( typeof handler !== 'function' ) { throw new Error ( `No route handler found for ${ method . toUpperCase ( ) } request at "${ path }"` ) ; } return handler ( this . contextMock , mockRequest , responseMock ) ; } }