Send an object to the export function in Express

I have been honing my TypeScript skills and encountered an issue. I am working with a class called Manager which oversees multiple 'sub' managers. In the index file, I instantiate the Manager class and invoke the load function. During loading, all 'sub' managers receive a reference to the main/only Manager instance, enabling them to interact with each other.

However, I now need to retrieve information from the 'sub' managers through a REST API endpoint. These endpoints are defined in routes:

index.ts

import "reflect-metadata";

import { createConnection } from "typeorm";
import { Request, Response } from "express";

import * as express from "express";
import * as bodyParser from "body-parser";

import { AppRoutes } from "./routes";
import { Manager } from "./manager";

createConnection().then(async (typeORMConnection) => {
    const manager = new Manager();

    manager.load().then(() => {
        console.log("Manager has loaded all managers");

        const expressApp = express();

        expressApp.use(bodyParser.json());
        expressApp.use(function(req, res, next) {
        res.header("Access-Control-Allow-Origin", "*");
        res.header("Access-Control-Allow-Methods", "*");
        res.header("Access-Control-Allow-Headers", "*");
        next();
        });

        // Loop over every route
        AppRoutes.forEach((singleRoute) => {

        // Generate Express route
        expressApp[singleRoute.method](singleRoute.path, (request: Request, response: Response, next: Function) => {
            singleRoute.action(request, response)
                .then(() => next())
                .catch((error) => next(error));
            });
        });

        // Start Express app
        expressApp.listen(3000);

        console.log("Express application is up and running on port 3000");
    });
}).catch((error) => console.log(`TypeORM connection error: ${error}`));

A typical route file includes:

routes.ts

import { getSpeakerById, getSpeakerAll } from "./controller/get";
import { enableSpeakerById, disableSpeakerById } from "./controller/put";

export const AppRoutes = [
    {
        path: "/speaker",
        method: "get",
        action: getSpeakerAll
    },
    {
        path: "/speaker/:id",
        method: "get",
        action: getSpeakerById
    },
    {
        path: "/speaker/:id/disable",
        method: "put",
        action: disableSpeakerById
    },
    {
        path: "/speaker/:id/enable",
        method: "put",
        action: enableSpeakerById
    },
];

The following Express endpoint file contains the actual logic:

controller/get.ts

import { Request, Response } from "express";
import { getManager } from "typeorm";

import { Speaker } from "../entity/Speaker";

const ping = require("ping");

export async function getSpeakerById(request: Request, response: Response) {
    const speakerRepository = getManager().getRepository(Speaker);
    const speakerObject = await speakerRepository.findOne(request.params.id);

    if (!speakerObject) {
        response.status(404);
        response.send("Speaker doesn't exist");
        response.end();
        return;
    }

    speakerObject.time = await ping.promise.probe(speakerObject.host);

    response.send(speakerObject);
}

export async function getSpeakerAll(request: Request, response: Response) {
    const speakerRepository = getManager().getRepository(Speaker);
    const speakerObjects = await speakerRepository.find();
    const speakerPromise = [];

    speakerObjects.forEach((speakerObject) => speakerPromise.push(ping.promise.probe(speakerObject.host)));

    const speakerResults = await Promise.all(speakerPromise);

    speakerResults.forEach((speakerResult, speakerIndex) => speakerObjects[speakerIndex].time = speakerResult.time);

    response.send(speakerObjects);
}

Now, the challenge lies in accessing the main Manager instance within the controller/get.ts without passing it as a parameter. Simply importing the Manager class and creating a new instance isn't viable since I only want to initiate the Manager once due to its internal logic involving intervals and instances from the Sonos package. If further clarification is required, feel free to request additional details.

Answer №1

Passing it as a parameter is definitely possible. You can easily incorporate this into your index.ts file:

// Setting up Express route
expressApp[singleRoute.method](singleRoute.path, (request: Request, response: Response, next: Function) => {
    singleRoute.action(request, response, manager)
        .then(() => next())
        .catch((error) => next(error));
    });
});

Make sure to update the signature of your controller methods when exporting them like so:

import { Manager } from '../manager';

export async function fetchUserById(request: Request, response: Response, manager: Manager) {
    ...
}

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

Dealing with popups in nightmarejs: what's the best approach?

Looking for guidance on managing website pop-up windows in nightmarejs. Specifically interested in tasks such as viewing a list of open windows, closing them, extracting data from the pop-ups, and potentially subscribing to popup creation events. Your ins ...

When trying to deploy create-react-app with an Express backend on Heroku, an error message about an invalid host header appears

Looking for help with the issue? Check out my minimal working example on GitHub. I've experimented with numerous approaches (all documented in the commits), but haven't found a solution yet. I am determined to keep pursuing this until I find an ...

Displaying Well-Formatted XML in Angular2 Using Typescript

After receiving this XML string from the server: <find-item-command xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" find-method="Criteria" item-class="com" only-id="false" xsi:schemaLocation=""> <criteria> <criterion> <descripto ...

Using props in the v-bind:src directive with Vue - a comprehensive guide!

I have a Vue application with a Block component that needs to display an image. The Block component is used multiple times in the App component, each time passing a value to determine which image src to choose from an array. When I try to print {{ this.Im ...

Provide an instance of mockClient for AWS SQSClient in a TypeScript class

I'm currently working on unit testing a piece of code that relies on a constructor with an SQSClient object for interacting with an sqs queue. To write effective unit tests, I need to mock the client so that I can test the code without actually access ...

Obtain the orientation of the threejs scene and camera to establish the initial perspective

Currently, I am facing challenges in configuring the default camera position and orientation for my THREE.JS demo. I aim to manually adjust the view/scene/camera through trackball interaction and then find a way to set the correct camera settings to establ ...

Having trouble sending an ajax request from localhost to a remote server

When attempting to make an ajax request (using jquery) from my local server to a remote page where I am the administrator, I encounter the following error: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin &ap ...

Using JSON input to add color to a d3 bullet chart

I am currently working with a D3 bullet chart example and trying to enhance it by incorporating different colors for the ranges directly into the JSON file. The link to the original example can be found here: . I need this customization because I require d ...

The hyperlink tag within the overlay div is unresponsive

I'm facing an issue with my overlay div (rb-overlay) that pops up when users click on a page option. The overlay takes up the entire page and includes a close button in the top right corner. However, I've noticed that the link at the end of the t ...

Which is more effective: Utilizing individual query functions or a single dynamic one?

Hey there! I'm currently in the process of developing the backend for a web application using node-postgres and I'm interested in hearing some feedback. I need to create basic insert queries for various tables, such as the users table, products t ...

What is the process for defining the root of a project in ESLint?

I've been working on a project using Next.js and Typescript. My imports look like this: import Component from "/components/Component/Component";, with the root directory being specified as /src. This setup works fine in Next.js, but ESLint k ...

Testing a NestJS service with multiple constructor parameters can be done by utilizing various techniques such as dependency

Content When testing a service that needs one parameter in the constructor, it's essential to initialize the service as a provider using an object instead of directly passing the service through: auth.service.ts (example) @Injectable() export class ...

Despite being deployed on Vercel, the process.env variables in Nextjs are still not functioning as expected

I'm currently working on a project that involves using 4 api keys that I need to keep hidden: STORYBLOK_API_KEY= EMAILJS_SERVICE_ID= EMAILJS_USER_ID= EMAILJS_TEMPLATE_ID= All of these keys are being accessed using process.env.XXX. What's inte ...

The Value of Kendo Data

Below is my current kendo code snippet: <script> $("#dropdowntest").kendoDropDownList({ optionLabel: "Select N#", dataTextField: "NNumber", dataValueField: "AircraftID", index: 0, ...

Display the first item last in an *ngFor loop in Nativescript Angular

I'm facing some confusion with the sorting of an array in JavaScript. Although the index, last, and first seem to be correct, the result is not as expected. Versions @angular/core: 4.1.0 nativescript-angular: 3.1.3 typescript: 2.4.0 Expected 1234 ...

How can we set up the Typescript Compiler to recognize typings and modules effectively?

I have been working on a TypeScript project with the following structure: <work folder>/Scripts/ (project root) +-- App +--- subfolder1 +--- subfolder2 +-- typings After openi ...

Parsing JSON sub items in Android application using Java

Here is a snippet of my PHP file: <?php $myObj = array( "name"=>"John" , "age"=>"30" , "post"=>[ "title"=>"What is WordPress" , "excerpt"=>"WordPress is a popular blogging platform" , ...

Creating a JavaScript function that increments or decrements a variable based on keyboard input is a useful feature

My goal is to have a count start at 100 and then either count up or down by 1 when a specific keyboard button is pressed. Currently, I am using the keys 8 and 2 on the keypad, which represent ascii numbers 104 and 98. So far, the code I have only allows f ...

What is the functionality of named function expressions?

After coming across an intriguing example in the book labeled as a "named function expression," I was curious to delve into its mechanics. While the authors mentioned it's not commonly seen, I found it fascinating. The process of declaring the functi ...

Troubleshooting Material-UI: The Mystery of the Missing Dialog

I have been struggling with getting a pop-up dialog to appear when a form is incorrectly filled out. Despite my efforts, the code that should trigger the dialog upon submission does not seem to be working as expected. The function renderError(), responsib ...