Skip to content

Commit

Permalink
feat: Adds decorator options to proxy route creator
Browse files Browse the repository at this point in the history
  • Loading branch information
hofmeister committed Jan 5, 2024
1 parent 04dd279 commit 88685e2
Showing 1 changed file with 35 additions and 6 deletions.
41 changes: 35 additions & 6 deletions index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,20 +3,35 @@
* SPDX-License-Identifier: MIT
*/

import Path from 'path';
import type { RequestOptions } from 'node:http';
import type { RequestHandler, Request } from 'express';
import type { ConfigProvider } from '@kapeta/sdk-config';

import { RequestHandler, Request } from 'express';
import Path from 'path';
import proxy from 'express-http-proxy';
import { ConfigProvider } from '@kapeta/sdk-config';

const DEFAULT_SERVICE_TYPE = 'web';

const DEFAULT_SERVICE_TYPE:ProxyServiceType = 'web';

export type ProxyServiceType = 'web' | 'rest' | 'http';
export type ProxyRequestDecorator = (serviceName:string, serviceType:ProxyServiceType, proxyReqOpts: RequestOptions, srcReq:Request) => RequestOptions
export type ProxyBodyDecorator = (serviceName:string, serviceType:ProxyServiceType, bodyContent: any, srcReq:Request) => any

export type ProxyRouteOptions = {
// Apply decorators to the request options before sending each request
requestDecorators?: ProxyRequestDecorator[]

// Apply decorators to the body before sending each request
bodyDecorators?: ProxyBodyDecorator[]
}

export const createProxyRoute = async (
provider: ConfigProvider,
name: string,
serviceType?: string
serviceType: ProxyServiceType = DEFAULT_SERVICE_TYPE,
opts: ProxyRouteOptions = {}
): Promise<RequestHandler> => {
let targetUrl = await provider.getServiceAddress(name, serviceType ?? DEFAULT_SERVICE_TYPE);
let targetUrl = await provider.getServiceAddress(name, serviceType);
if (!targetUrl) {
throw new Error(`Service ${name} not found`);
}
Expand All @@ -33,10 +48,24 @@ export const createProxyRoute = async (
https: urlParts.protocol === 'https',
timeout: 120000,
limit: '1000mb',
proxyReqBodyDecorator: function (bodyContent, srcReq) {
if (opts?.bodyDecorators) {
opts.bodyDecorators.forEach((decorator) => {
bodyContent = decorator(name, serviceType, bodyContent, srcReq);
});
}
return bodyContent;
},
proxyReqOptDecorator: function (proxyReqOpts, srcReq) {
if (proxyReqOpts.headers) {
delete proxyReqOpts.headers['connection'];
}

if (opts?.requestDecorators) {
opts.requestDecorators.forEach((decorator) => {
proxyReqOpts = decorator(name, serviceType, proxyReqOpts, srcReq);
});
}
return proxyReqOpts;
},
proxyReqPathResolver: function (req: Request) {
Expand Down

0 comments on commit 88685e2

Please sign in to comment.