diff --git a/source/interfaces/Proxy.ts b/source/interfaces/Proxy.ts index 43c15e6..072f71d 100644 --- a/source/interfaces/Proxy.ts +++ b/source/interfaces/Proxy.ts @@ -1,5 +1,7 @@ +import { RequestHandler } from 'http-proxy-middleware'; + export default interface Proxy { name: string; host: string; - proxy: Function; + proxy: RequestHandler; } diff --git a/source/proxy.ts b/source/proxy.ts index 463f7ef..3a52740 100644 --- a/source/proxy.ts +++ b/source/proxy.ts @@ -138,4 +138,20 @@ export class ProxyManager { return route; } + + /** + * Resolve the current proxy for a given route. + * + * @param route The route + * @return Resolved proxy + */ + resolveRouteProxy(route: Route): RequestHandler | undefined { + const current = this.getCurrent(); + + if (route.proxy !== undefined) { + return route.proxy?.proxy; + } + + return current?.proxy; + } } diff --git a/source/routes.ts b/source/routes.ts index 9238f0c..e45e9f9 100644 --- a/source/routes.ts +++ b/source/routes.ts @@ -130,4 +130,11 @@ export class RouteManager { ], }); } + + /** + * Find a route by path. + */ + findRouteByPath(path: string) { + return this.routes.find((route) => route.path === path); + } } diff --git a/source/server.ts b/source/server.ts index 0ef76f5..a6dcf44 100644 --- a/source/server.ts +++ b/source/server.ts @@ -54,6 +54,18 @@ export function createServer(options = {} as ServerOptions): Server { uiManager.drawRequest(req, res, next) ); + expressServer.use((req: Request, res, next) => { + const route = routeManager.findRouteByPath(req.path.replace(basePath, '')); + if (route) { + const proxy = proxyManager.resolveRouteProxy(route); + if (proxy) { + return proxy?.(req, res, next); + } + } + + next(); + }); + /** * Merge method with current selected override. * @@ -89,20 +101,6 @@ export function createServer(options = {} as ServerOptions): Server { return typeof attribute === 'function' ? attribute(req) : attribute; } - /** - * Get the route current proxy. - * - * @param route The route - * @return Current proxy - */ - function getRouteProxy(route: Route) { - if (route.proxy !== undefined) { - return route.proxy; - } - - return proxyManager.getCurrent(); - } - /** * Get the method content. * @@ -184,11 +182,6 @@ export function createServer(options = {} as ServerOptions): Server { ): void { const mergedMethod = mergeMethodWithSelectedOverride(method); const { code = 200 } = mergedMethod; - const routeProxy = getRouteProxy(route); - - if (routeProxy) { - return routeProxy.proxy(req, res); - } const content = getContent(mergedMethod, route.path, req, res); const headers = resolveMethodAttribute(mergedMethod.headers, req);