I am currently developing a Node.js/express application in typescript that involves a proxy route with specialized business logic for determining the proxy URL:
import proxy from "http-proxy-middleware";
const controller = diContainer.get<IController>(TYPES.Controller);
const app = express();
app.use("/customProxy", controller.handleProxy());
@injectable()
export class Controller implements IController {
public handleProxy(): RequestHandler {
return proxy(
"**", // proxy all incoming routes
{
router: (req: Request) => {
// custom logic to translate route
return customRouteBasedOnIncomingRequest;
},
onProxyRes: (proxyRes: http.IncomingMessage, req: http.IncomingMessage, res: http.ServerResponse) => {
// custom logic to set outgoing response
res.setHeader("custom", "header")
},
}
});
}
}
I have been exploring the possibility of using mock-express-request to simulate Request/Response objects. However, I am uncertain how to integrate it with the proxy
.
Is there a method to inject a mock that can intercept the http client sending the proxy request? Ideally, I would like to incorporate this function into the Controller
:
public mockedHttpServer(req: Request):Response
{
const res = new MockExrpessResponse();
if (req.url == "http://expected.url"){
res.write("success");
res.statuscode = 200;
}
else{
res.statuscode = 404;
}
return res;
}
I attempted to intervene with proxy.onProxyReq
and utilize proxyReq.abort()
, followed by writing directly to the Response
. Unfortunately, this approach did not prevent an actual request from being sent out.
Are there any alternative methods to tap into the http stack and mimic the network io operations?