Skip to content

Commit

Permalink
Use axios to bypass http-middleware when proxy is configured (#881)
Browse files Browse the repository at this point in the history
* Use axios to bypass http-middleware when proxy is configured

* Fix imports
  • Loading branch information
sudharsan-selvaraj authored Nov 14, 2023
1 parent afa8793 commit dfe040d
Showing 1 changed file with 26 additions and 2 deletions.
28 changes: 26 additions & 2 deletions src/wd-command-proxy.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,21 @@
import { Request, Response, NextFunction } from 'express';
import { HttpsProxyAgent } from 'https-proxy-agent';
import { HttpProxyAgent } from 'http-proxy-agent';
import { createProxyMiddleware } from 'http-proxy-middleware';
import _ from 'lodash';
import { unblockDevice } from './data-service/device-service';
import logger from './logger';
import axios from "axios";

const remoteProxyMap: Map<string, any> = new Map();
const remoteHostMap: Map<string, any> = new Map();

function getProxyServer() {
return process.env.HTTPS_PROXY || process.env.HTTP_PROXY;
}

export function addProxyHandler(sessionId: string, remoteHost: string) {
const proxyServer = process.env.HTTPS_PROXY || process.env.HTTP_PROXY;
const proxyServer = getProxyServer();
logger.info(`proxyServer: ${JSON.stringify(proxyServer)}`)
const config: any = {
target: new URL(remoteHost).origin,
Expand All @@ -24,6 +31,7 @@ export function addProxyHandler(sessionId: string, remoteHost: string) {
sessionId,
createProxyMiddleware(config)
);
remoteHostMap.set(sessionId, remoteHost);
}

export function removeProxyHandler(sessionId: string) {
Expand Down Expand Up @@ -56,12 +64,28 @@ function getSessionIdFromUr(url: string) {
}

async function handler(req: Request, res: Response, next: NextFunction) {
const proxyServer = getProxyServer();
const sessionId = getSessionIdFromUr(req.url);

if (!sessionId) {
return next();
}
if (remoteProxyMap.has(sessionId)) {
remoteProxyMap.get(sessionId)(req, res, next);
if(proxyServer) {
const response = await axios({
method: req.method,
url: new URL(req.path, new URL(remoteHostMap.get(sessionId)).origin).toString(),
data: req.body,
params: req.query,
validateStatus: () => true,
httpsAgent : new HttpsProxyAgent(proxyServer),
httpAgent : new HttpProxyAgent(proxyServer),
proxy: false
})
res.status(response.status).json(response.data);
} else {
remoteProxyMap.get(sessionId)(req, res, next);
}
if (req.method === 'DELETE') {
logger.info(
`📱 Unblocking the device that is blocked for session ${sessionId} in remote machine`
Expand Down

0 comments on commit dfe040d

Please sign in to comment.