Imitate a Node.js Proxy

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?

Answer №1

If you're looking for an alternative, you might want to check out:

By intercepting the outgoing http requests and using a mock server, you can avoid having to inject mocks directly into your code.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The Typescript compiler will continue to generate JavaScript code even if there are compilation errors

As a fresh learner of TypeScript, I have been experimenting with some basic concepts. Below is the code from my file app1.ts: class Monster { constructor(name, initialPosition) { this.name = name; this.initialPosition = initialPosition ...

Struggling to understand how to properly 'map' my data from the response in Next.js 13 using Typescript

Just a few days into my journey with next.js, and I'm already facing a challenge in figuring out how to fetch data from an API. In regular React, I would typically use useState and useEffect for managing state and fetching data. But when it comes to n ...

Changes made to the source files in Webpack dev server combined with React and Typescript are not being successfully

I'm embarking on a new project to develop a small app using React, TypeScript, and Webpack for building. I found this helpful article to guide me through the process: https://www.typescriptlang.org/docs/handbook/react-&-webpack.html All the proje ...

Adjust the appearance of matSelect when the selection menu is activated

What is the best way to adjust mat-select properties when its options are open? <mat-select class="selector"> <mat-option><mat-option> </mat-select> .selector:focus { color: green; } I attempted using focus, but ...

Having trouble debugging TypeScript files in Chrome following an Angular update

I have been experimenting with writing a basic app using Angular 4.2.5 to expand my knowledge. Previously, I was able to debug the TypeScript files in Chrome without any issues. However, after updating to Angular 5.2.7, I am no longer able to view the Type ...

The ES6 import feature conceals the TypeScript definition file

I currently have two definition files, foo.d.ts and bar.d.ts. // foo.d.ts interface IBaseInterface { // included stuff } // bar.d.ts interface IDerivedInterface extends IBaseInterface { // more additional stuff } Initially, everything was funct ...

What is the best way to locate two specific fields from two distinct models within mongoDB?

The initial model is known as --> Post The subsequent model is referred to as --> User locate ({fieldA = true in Post} and locate ({fieldB = true in User}) then distribute the outcome as a JSON document. ...

Transform a collection of objects into instances of a class

I have a scenario where I am fetching an array of objects from PHP and my goal is to transform this data into instances of a class called ContentData. The current solution that I have seems to work fine, but deep down I sense that there might be a more el ...

Tips on implementing Piwik JavaScript code within app.js on Express

I am trying to implement Piwik tracking on my Express website using JavaScript code. I placed the code in my app.js file but encountered an error. Here is the JavaScript code snippet: <script type="text/javascript"> var _paq = _paq || []; ...

Step-by-step guide on activating a button only when all form fields are validated

My very first Angular 5 project. I've gone through resources like: https://angular.io/guide/form-validation and various search results I looked up, only to realize that they are all outdated. In my form, I have several input fields such as: <for ...

Comparing vue.component to using import statements inside a component

After setting up a vue2 library using vue-cli, I have numerous components included in the index.ts file as shown below: import MyComponent1 from './components/MyComponent1.vue'; import MyComponent2 from './components/MyComponent2.vue'; ...

Tips for accessing child elements within an Angular component

I'm struggling to get a reference of child elements within a component. I have experimented with ElementRef, TemplateRef, QueryList, ViewChild, ViewChildren, ContentChild, and ContentChildren without success. <app-modal> <section #referenc ...

Data is not being stored in req.session

I am currently working on setting up a login system for users to register and sign in to a website, allowing them to edit their personal information once logged in. In order to determine if a user is logged in, I have been trying to set req.session.isLogg ...

Deploy your Express app on Heroku and leverage Parse as your backend

I'm currently working on setting up my express app to use Parse for data handling. However, since Parse's hosting options for web apps have limitations, I've decided to host my app on Heroku instead. While I've successfully set up my ex ...

The Fetch API seems to be having trouble loading the data from localhost:300

I am facing an issue with my express-js server that returns an array of data. I want to use the Fetch API to make a request and display this list on the screen. However, every time I try to make a request, I encounter an error stating "Fetch API cannot loa ...

Supplying information to my ejs template while redirecting

I am currently working on a feature that involves sending data from the login page to the home page when the user is redirected. This data will then be used in the home EJS file. Below is the code snippet I have implemented: module.exports = functio ...

What strategies can be used to refactor nested callbacks in node and effectively pass parameters to each function within the callbacks?

I am currently in the process of refactoring some JavaScript code within a Node environment, and I'm encountering difficulties when it comes to passing parameters to functions that serve as callbacks for other functions. Here is an example of my curre ...

Styling Form validation with Ant Design

Can a className prop be included in the Form.Item validation? <Form.Item name="username" rules={[ { required: true, message: '...' }, className="customValidation" //<- attempting to add a className but it is not fu ...

Steps for generating a signal that postpones the primary signal and promptly resets

I am looking to create a signal that will automatically switch to an underlying signal or memo after a specific delay, and reset immediately if the primary signal is cleared. The code snippet below illustrates my desired functionality. import { render } fr ...

Unable to define the type for the style root in Typescript

I am encountering an error that is asking me to code the following types in the root tag: No overload matches this call. Overload 1 of 2, '(style: Styles<Theme, {}, "root">, options?: Pick<WithStylesOptions<Theme>, "fli ...