Creating a new ES-6 class to extend express-js: Issues with binding getter and setter properties

I am intrigued by the idea of utilizing Express within an extended class. My goal is to create getter and setter methods for a property, but I'm facing the issue of these methods not being bound to the instances as desired. One way to work around this is to implement a custom getter and setter method and bind it in the constructor, although this approach doesn't feel quite right.

const express = require("express");


export default class Application extends express {
    _endpoints;

    constructor() {
        super();
        this._endpoints = null;
    }
    get endpoints() {
        return this._endpoints;
    }

    set endpoints(paths: []) {
        this._endpoints = new Set(...paths);
    }
}


const myApp = new Application();
console.log(myApp) // ...express-app-object, _endpoints, and nothing related to the getter and setter defined.
console.log(myApp._endpoints) // null
console.log(myApp.endpoints) // undefined

Answer №1

Interestingly, the issue stems from the nature of express not being a class or constructor, but rather a factory function. When you invoke super(), it actually calls express(), creating a completely separate object that lacks your object's prototype. While referencing myApp._endpoints works due to your constructor assigning that property to the object produced by express(), this new object does not inherit your prototype - it is an entirely distinct entity generated by Express.

If you eliminate extends express and disable super(), you'll observe that everything functions as expected.

If you substitute 'express' with another defined class in JavaScript, such as className(), the endpoints() getter operates smoothly.

Hence, attempting to extend express in this fashion is not viable.

The express prototype remains accessible, allowing for additional modifications just like before the advent of the class syntax.


I highly discourage using a class in this scenario since it may mislead other developers into thinking they can define methods for the class, which isn't the case here.

Instead, establish your own factory function that invokes the express factory function and then appends properties to the resultant object:

// custom factory function for the application
function Application() {

    const app = express();

    // include instance properties
    app._endpoints = null;

    // incorporate getters/setters
    Object.defineProperty(app, "endpoints", {
        get: function () {
            return this._endpoints;
        },
        set: function (paths: any[]) {
            this._endpoints = new Set([...paths]);
        },
        enumerable: true,
        configurable: true,
    });
    return app;
}

This approach can be utilized either as:

app = Application();

or:

app = new Application();

Answer №2

class WebApp extends express {
    constructor() {
        super();
        this._routes = null;
    
        Object.defineProperty(this, "routes", {
            get: function () {
                return this._routes;
            },
            set: function (paths) {
                this._routes = new Set([...paths]);
            },
            enumerable: true,
            configurable: true,
        });
    }
}

Usage Example:

const webApp = new WebApp();
console.log(webApp.routes); // null
webApp.routes = ['/home', '/about'];
console.log(webApp.routes); // Set(2) { '/home', '/about' }

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

Steps to verify the timepicker for accuracy and consistency throughout different time periods

I am currently working on validating a time picker for a project. I found a helpful example for date validation at http://jqueryui.com/resources/demos/datepicker/date-range.html but I need to adapt it for a time picker. Specifically, I need to ensure tha ...

Ways to obtain data in JavaScript function from HTML

Struggling to pass the key from a database query in HTML using PHP to a JavaScript function? You're not alone. The challenge lies in passing the field_id to the updateRecords() JS function through the onClick() event of an HTML button. Previously, se ...

Checking if Javascript is loaded using a JQuery getScript call

I would like to improve the performance by loading a JavaScript file upon a click event instead of during the initial page load. How can I check if the JavaScript file has already been loaded? Currently, I am using a global variable to track the 'loa ...

Issue with making Flickr API request using XMLHttpRequest receiving an unsuccessful response

I'm having issues trying to retrieve a JSON list from Flickr using plain JavaScript and XMLHttpRequest. Here is an example of an AJAX call without a callback function that is not functioning properly: var url = "https://api.flickr.com/services/feed ...

Can we determine the data type of an object based on a property within an interface?

Here is my current interface: MyInterface { prop1?: string, prop2?: string, } Now, I am looking to introduce an alternative property that mirrors the content of the existing properties but also infers if any properties are defined. For instance: ...

JavaScript: How to identify and select a specific item from a context menu

Currently diving into the world of JavaScript, so please keep that in mind when explaining. My main goal is to figure out a way to detect when a user triggers a right-click or uses the context menu from the keyboard. Specifically, I want to know if they s ...

Deny access to the viewing feature for unauthorized users

Objective: To restrict access to the profile page only for logged-in users. The authentication is done through mongodb and passport-local. Existing Code: Below is the express route used to verify if the request is authenticated. app.get('/loggedin ...

What is the reason that TypeScript cannot replace a method of the base class with a subtype?

Here's a straightforward example. type Callback<T> = (sender: T) => void; class Warehouse<T> { private callbacks: Callback<T>[]; public constructor(callbacks: Callback<T>[]) { this.callbacks = callbacks; ...

Accessing information independent of Observable data in TypeScript

When attempting to send an HttpRequest in Typescript, I encountered an issue where the received data could not be stored outside of the subscribe function. Despite successfully saving the data within the subscribe block and being able to access it there, ...

Error Found: Syntax Error - 'if' statement not recognized

if (fname == null || fname == "") { Receiving an error message "uncaught syntax error:unexpected token if in line 13". The error indicates "SyntaxError: missing variable name" when using Javascript lint function validateRegistration() { var emailReg ...

Ways to identify browser version in Angular 4 to discourage IE usage

Is there a method in Angular 4 (TypeScript) for detecting the browser type? I am currently working with Angular 4 and would like to explore options for identifying the browser type when my application is loaded. I specifically want to prevent my applicati ...

Is there a way for me to initialize a PHP array using data from an AJAX call?

Trying to fetch data from an ajax request and potentially set a php array seems challenging as one operates on the client side while the other on the server side. Below is the code: HTML page: <?php foreach ($products as $product): ?> <li> ...

To fully utilize the capabilities of WebGL, ensure it is enabled while using the nightwatch.js/selenium

There's a perplexing issue I've encountered while attempting to launch a page containing WebGL content using a nightwatchJS-based framework: When opening the page directly in Chrome, WebGL is properly detected. The Graphics Feature Status in ...

Executing methods sequentially in the ngOnInit lifecycle hook consecutively

Working with Angular15 has presented me with a challenge. In my app.component.ts file, I have two methods: “ngOnInit()”, as shown below. public ngOnInit(): void { this.getToken(); this.UserLoggedIn(); } I am looking to run the above two functions in ...

Exporting an indexed geometry with a draw range using GLTFExporter in Three.js: What's the best approach?

I am encountering a specific issue where I need to export an indexed geometry with a draw range. Unfortunately, the GLTFExporter does not support this feature, as indicated by the comment in the code: // @TODO Indexed buffer geometry with drawRange not su ...

Use the reduce method to convert a JavaScript object from 2 to 1

Looking to create a function that can transform these objects: const input1 = [ { id: "lkhj68C13h8uWh4RJz7", post: "on XSS attacks", gender: "Littérature", postId: "cxTbP5EZjNCxw7rD60L7", }, { ...

Explore various queries and paths within MongoDB Atlas Search

I am currently working on developing an API that can return search results based on multiple parameters. So far, I have been able to successfully query one parameter. For example, here is a sample URL: http://localhost:3000/api/search?term=javascript& ...

Unleashing the Power of Resetting CSS Class Attributes in Twitter Bootstrap

Last year, @Andres Ilich shared a remarkably elegant solution for centering the navigation bar in Bootstrap. Here is an excerpt from the answer he posted: Visit here for more details. <div class="navbar navbar-fixed-top center"> <div class=" ...

What is the process for passing a component as a parameter to a function within a different component?

Within my scenario, I have a series of components '1,2,3,...' imported into another primary component 'A'. Within component 'A', certain operations are performed and a filtered component is then returned from the list of compo ...

Creating HTML output using an input checkbox in combination with JavaScript

I am creating a dynamic string to be inserted into a div using JavaScript. The issue I am facing involves the onclick attribute of an input checkbox. I want to pass a unique id value with each click of the checkbox. Below is the code snippet I am currently ...