Skip to content

Commit

Permalink
feat: Refactor to use plain express routes (#4)
Browse files Browse the repository at this point in the history
BREAKING CHANGES: API change adjusted for V2
  • Loading branch information
hofmeister committed Dec 13, 2023
1 parent d9c42b9 commit 3482596
Show file tree
Hide file tree
Showing 3 changed files with 794 additions and 422 deletions.
72 changes: 19 additions & 53 deletions index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,68 +5,34 @@

import Path from 'path';

import express, { Router } from 'express';
import { RequestHandler } from 'express';
import proxy from 'express-http-proxy';
import Config, { ConfigProvider } from '@kapeta/sdk-config';
import { ConfigProvider } from '@kapeta/sdk-config';

const DEFAULT_SERVICE_TYPE = 'web';

export class ProxyRoute {
private readonly _name: string;
private readonly _path: string;
private readonly _serviceType: string;
private readonly _router: Router;

private _targetUrl: string;
private _ready: boolean;

constructor(name: string, path: string, serviceType: string) {
this._name = name;
this._path = path;
this._serviceType = serviceType ?? DEFAULT_SERVICE_TYPE;
this._targetUrl = `http://${name.toLowerCase()}`;
this._ready = false;
this._router = express.Router();
export const createProxyRoute = async (provider: ConfigProvider, name: string, serviceType?: string):Promise<RequestHandler> => {
let targetUrl = await provider.getServiceAddress(name, serviceType ?? DEFAULT_SERVICE_TYPE);
if (!targetUrl) {
throw new Error(`Service ${name} not found`);
}

Config.onReady(async (provider) => {
await this.init(provider);
});
if (!targetUrl.endsWith('/')) {
targetUrl += '/';
}

/**
* Called automatically during startup sequence.
*
* @param {ConfigProvider} provider
* @return {Promise<void>}
*/
async init(provider: ConfigProvider) {
this._targetUrl = await provider.getServiceAddress(this._name, this._serviceType);
this._ready = true;
const urlParts = new URL(targetUrl);

if (!this._targetUrl.endsWith('/')) {
this._targetUrl += '/';
}
console.log('Proxy route ready for %s --> %s', name, targetUrl);

const urlParts = new URL(this._targetUrl);
return proxy(urlParts.host, {
https: urlParts.protocol === 'https',
proxyReqPathResolver: function (req) {
const [path, query] = req.url.split('?');

this._router.use(
this._path,
proxy(urlParts.host, {
https: urlParts.protocol === 'https',
proxyReqPathResolver: function (req) {
const [path, query] = req.url.split('?');
return Path.join(urlParts.pathname, path) + (query ? '?' + query : '');
},
})
}

return Path.join(urlParts.pathname, path) + (query ? '?' + query : '');
},
})
);
console.log('Proxy route ready for %s. %s --> %s', this._name, this._path, this._targetUrl);
}

/**
* Returns expressjs Router object that contains proxy
*/
toExpressRoute() {
return this._router;
}
}
Loading

0 comments on commit 3482596

Please sign in to comment.