feat(proxy-backend): more proxy config tweaks and docs

This commit is contained in:
Fredrik Adelöw
2020-08-26 16:18:21 +02:00
parent d0cce48b14
commit 6d774764cd
7 changed files with 95 additions and 20 deletions
@@ -26,6 +26,7 @@ describe('createRouter', () => {
const router = await createRouter({
config,
logger,
pathPrefix: '/proxy',
});
expect(router).toBeDefined();
});
+39 -3
View File
@@ -17,21 +17,57 @@
import { Config } from '@backstage/config';
import express from 'express';
import Router from 'express-promise-router';
import createProxyMiddleware from 'http-proxy-middleware';
import createProxyMiddleware, {
Config as ProxyConfig,
Proxy,
} from 'http-proxy-middleware';
import { Logger } from 'winston';
export interface RouterOptions {
logger: Logger;
config: Config;
// The URL path prefix that the router itself is mounted as, commonly "/proxy"
pathPrefix: string;
}
// Creates a proxy middleware, possibly with defaults added on top of the
// given config.
function buildMiddleware(
pathPrefix: string,
route: string,
config: string | ProxyConfig,
): Proxy {
const fullConfig =
typeof config === 'string' ? { target: config } : { ...config };
// Default is to do a path rewrite that strips out the proxy's path prefix
// and the rest of the route.
if (fullConfig.pathRewrite === undefined) {
const routeWithSlash = route.endsWith('/') ? route : `${route}/`;
fullConfig.pathRewrite = {
[`^${pathPrefix}${routeWithSlash}`]: '/',
};
}
// Default is to update the Host header to the target
if (fullConfig.changeOrigin === undefined) {
fullConfig.changeOrigin = true;
}
return createProxyMiddleware(fullConfig);
}
export async function createRouter(
options: RouterOptions,
): Promise<express.Router> {
const router = Router();
const proxyConfig = options.config.get('proxy') ?? {};
const proxyConfig = options.config.getOptional('proxy') ?? {};
Object.entries(proxyConfig).forEach(([route, proxyRouteConfig]) => {
router.use(route, createProxyMiddleware(proxyRouteConfig));
router.use(
route,
buildMiddleware(options.pathPrefix, route, proxyRouteConfig),
);
});
return router;
@@ -40,6 +40,7 @@ export async function startStandaloneServer(
const router = await createRouter({
config,
logger,
pathPrefix: '/proxy',
});
const service = createServiceBuilder(module)
.enableCors({ origin: 'http://localhost:3000' })