Skip to content

Commit

Permalink
feat(proxy): use a middleware to proxy routes
Browse files Browse the repository at this point in the history
Fix #50
  • Loading branch information
fsmaia committed Feb 12, 2021
1 parent 2b63925 commit dfdf880
Show file tree
Hide file tree
Showing 4 changed files with 38 additions and 20 deletions.
4 changes: 3 additions & 1 deletion source/interfaces/Proxy.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { RequestHandler } from 'http-proxy-middleware';

export default interface Proxy {
name: string;
host: string;
proxy: Function;
proxy: RequestHandler;
}
16 changes: 16 additions & 0 deletions source/proxy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
}
7 changes: 7 additions & 0 deletions source/routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -130,4 +130,11 @@ export class RouteManager {
],
});
}

/**
* Find a route by path.
*/
findRouteByPath(path: string) {
return this.routes.find((route) => route.path === path);
}
}
31 changes: 12 additions & 19 deletions source/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*
Expand Down Expand Up @@ -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.
*
Expand Down Expand Up @@ -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);
Expand Down

0 comments on commit dfdf880

Please sign in to comment.