Invoke the router function dynamically

I am looking for a way to simplify route registration without manually writing out

app.get('/', function (req, res, next) { });
each time. I want to automate this process by passing in a router object like the one below...

{ 
    path: '',
    method: 'GET',
    function: 'test'
}

Everything works fine until it comes to actually executing the function.

The problem is with how I am attempting to call the function. Instead of executing it, I am only referencing it.

Here is the code responsible for calling the function.

this.routes.forEach((route: IRouter) => {
    const path = this.basePath + '/' + route.path;
    const requestMethod = route.method.toLowerCase();

    this.app[requestMethod](path, this[route.function]());
});

As you can see in the this.app line, I am trying to call the function without passing in necessary parameters like res, req, next.

Is there a way in Express to access these parameters through the app instance, since removing the () from the function call doesn't actually execute it?

Any assistance would be highly appreciated.

Answer №1

Depending on the output of this[route.function](), the functionality should work accordingly. For instance, if the test function is defined as follows:

test () {
    return (req, res, next) => {...}
}

Then there should be no issues with it working. However, if the function is structured like this:

test (req, res, next) {...}

In this case, the function should be executed when adding the route handler. If you don't intend to pass any parameters to the functions, it's advisable to go with the second test function and bind it without executing, as shown below:

class Foo () {
  constructor (config) {
    const { basePath } = this

    this.routes.forEach((route: IRouter) => {
      const path = `${basePath}/${route.path}`
      const requestMethod = route.method.toLowerCase()

     this.app[ requestMethod ](path, this[ route.function ].bind(this))
    })
  }

  test (req, res, next) {
    // ...
  }
}

This approach helps in avoiding unnecessary function creation.

Additionally, it's recommended to use fn instead of function in your route object to avoid conflicts with reserved keywords. While it may still function with function, using fn is a safer choice to prevent potential issues.

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

What factors outside of the program could potentially lead to the splice function not functioning as expected?

Within my code, I encountered a peculiar issue involving a splice line along with debug lines on both sides. Take a look: const obj = { x:[1,2], y:{t:"!!!"} } const lenBefore = S.groupings.length const ret = S.groupings.splice(gix, 0, obj) console.log(`${ ...

Removing an item from an ng-repeat loop while also dealing with a FormController within

I am encountering a significant issue with form inputs nested within the ng-repeat directive. I require an input that is an array and can vary in size; allowing users to add or remove parts of the form. Within the ng-repeat directive, there is an ng-form ...

Having issue with jQuery popup not functioning correctly on the right side with the contact form. Is there anyone who knows how

Looking for a side slide popup that only accepts paragraph content? Want to add a contact form to it? Check out this fiddle - link here For a working example, visit - $(function() { // Slide from right to left $('#test2').PopupLayer({ ...

Which is the best choice for a large-scale production app: caret, tilde, or a fixed package.json

I am currently managing a sizeable react application in production and I find myself undecided on whether it is more beneficial to use fixed versions for my packages. Some suggest that using the caret (^) is a safer route, but I worry that this could poten ...

Adjusting the rotation transform by deleting and reapplying canvas is causing the chart to not display data after redrawing

I am facing a challenge with my previous issue and I am exploring different solutions. One approach I am considering is to remove the canvas element completely and then re-add it, effectively resetting all rotations on the canvas. Although this method alm ...

Problem with selecting odd and even div elements

I have a div populated with a list of rows, and I want to alternate the row colors. To achieve this, I am using the following code: $('#PlatformErrorsTableData').html(table1Html); $('#PlatformErrorsTableData div:nth-child(even)').css(" ...

When selecting an old list, only the most recently created ID is displayed, rather than the ID of the specific list being

I've set up a dashboard where I can create lists and have them displayed on the screen, but there seems to be an issue when trying to open any list as only the last created one opens. Can anyone point out what mistake I might be making? The technologi ...

Keep the sub-menu in a kendo context menu from closing until the user either hovers over another menu item or clicks outside of the current item

Please take a look at this example: Due to the small size of sub-items, the sub-menu closes quickly when hovering over the menu and losing focus. My goal is to keep an opened sub-menu from closing until the user hovers over another menu item or clicks on ...

How to Share Your Vuejs Component with the World by Publishing it on npm

I have recently developed a Vue.js 2 project using webpack which consists of 2 components. My goal is to share this project as an npm package so that the components can be easily reused in multiple projects. After publishing the project on npm with npm pu ...

Difficulty encountered when consolidating intricate data attributes into a single array

I have a task to tackle in the code snippet below. My goal is to collect all the data in the age attributes and store them in a single array, formatting it as shown here: output = [48, 14, 139, 49, 15, 135, 51, 15, 140, 49, 15, 135, 51, 15, 140, 52, 16, ...

Embed a javascript tag to print a PDF document

I have been struggling with printing a PDF file using JavaScript. I attempted to use the embed trick suggested in this Silent print a embedded PDF but unfortunately, the print function remained undefined. Then, I tried another approach using an Iframe and ...

A guide on importing gLTF files into three.js

I've been having some trouble uploading a gLTF file using three.js. Despite fixing some errors, I'm still greeted with a black screen. One solution was adding this to my chrome target directory: ‘path to your chrome installation\chrome.exe ...

Callbacks for AJAX responses that are asynchronous

After using AJAX in a limited and straightforward manner for some time, I find myself currently debugging a web application that heavily relies on JavaScript and JQuery for client-side coding. One issue that has caught my attention is the possibility of mu ...

Bar chart in Chart.js becomes crowded and illegible on smaller screens due to overlapping bars

Hello there! I've encountered an issue where the bar chart overlaps when the screen width is too low. It seems to be related to the maintainAspectRatio property, which I set to false because I wanted the charts to shrink only in width, not in both axe ...

Encountering an issue: Unable to initiate a local server when running `npm start`

Currently diving into the world of React, I successfully set up a React app. However, upon running npm install after typing cd davidsapp, I encountered numerous warnings and errors. Subsequently, when issuing the command npm start, all of the errors are di ...

An issue occurred with building deployments on Vercel due to a typing error

When attempting to deploy my build on Vercel, I encountered an error. The deployment works fine locally, but when trying to build it on vercel, the following error occurs: [![Type error: Type '(ref: HTMLDivElement | null) => HTMLDivElement | null&a ...

What is the best way to link function calls together dynamically using RXJS?

I am seeking a way to store the result of an initial request and then retrieve that stored value for subsequent requests. Currently, I am utilizing promises and chaining them to achieve this functionality. While my current solution works fine, I am interes ...

How can you use CSS animations to animate two images in a way that hides one while showing the other?

click here for the image link visit this webpage for the link I need I am looking to add an animated section to my website. The inspiration comes from the webpage linked above, where images slide down one after another in a seamless manner. I attempted t ...

Leveraging the replace feature within Selenium IDE

After extracting information from a webpage, I found a string that read "price: $30.00" which I saved as "x." What I really needed was just the numbers - "30.00". I attempted to use x.replace(), but unfortunately it didn't work out. If anyone could as ...

Creating a personalized to-do list feature in NodeJs for exclusive user access: A step-by-step guide

After pondering over this issue for the past few days, I am still trying to grasp it. My web app allows users to login and create a list of students. My goal is to ensure that only the user who created the list can view it. Below is my progress so far. Co ...