Unlock the power of asynchronous dependencies on a global scale with Inversify

I'm looking to resolve an asynchronous dependency at the top level without relying on top-level awaits.

Currently, I've implemented a temporary solution by defining an asynchronous function getService() in the controller file. However, this approach requires me to call the getService() function for each route declared in the controller file.

This is my current code:

// something.controller.ts

const router = Router();

async function getService() {  // temporary solution
    return await container.getAsync<IService>(TYPES.Service))
}


router.get("/collection",
    paginateCollectionSchema,
    validateRequestSchema,

    async (req, res) => {
        const service = await getService(); // this needs to be done for each route
        const paginationSettings = await service.getSome(req.query.limit, req.query.offset);
        const pagination = paginate("/collection", paginationSettings);

        return res.json(pagination)
    },
);


...

export router;

What I would like to achieve is something like this:

// something.controller.ts

const router = Router();

// obtain service once without using top-level await

router.get("/collection",
    paginateCollectionSchema,
    validateRequestSchema,

    async (req, res) => {
        // no need to obtain service
        const paginationSettings = await service.getSome(req.query.limit, req.query.offset);
        const pagination = paginate("/collection", paginationSettings);

        return res.json(pagination)
    },
);


...

export router;

Answer №1

To ensure that an asynchronous initialization process completes before your server starts running and to use the result as a regular variable throughout your server, you can delay the server start until the asynchronous result is available. This way, you can assign the result to a variable and reference it as needed in any of the server request handlers.

If you require the value in another module, you can create a synchronous getter function that exports the variable for retrieval (as direct export is not possible).

It's worth noting that the introduction of top-level await was to simplify solutions for this type of issue.

The code structure is not fully revealed, but the concept is as follows:

// The variable at the top scope can be utilized in the code
// after the server is started
let mainService;

getService().then(service => {
    mainService = service;
    // Delay server start until service is available
    app.listen(...);
}).catch(err => {
    console.log("Failed to start server", err);
});

app.get((req, res) => {
    // The mainService variable can be used directly here
});

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

Enhancing ES6 capabilities with Angular polyfills

While exploring the Angular documentation and various online resources about Angular, I came across a question. If all code is written in Typescript, why would we need ES6 polyfills? My understanding is that webpack eventually transpiles the code to ES5, s ...

Errors arose due to the deployment of TypeScript decorators

Using TypeScript in a brand new ASP.NET Core project has brought some challenges. We are actively incorporating decorators into our codebase. However, this integration is causing numerous errors to appear in the output of VS2015: Error TS1219 Experim ...

How can I send a variety of different MongoDB queries to EJS?

After a user submits a form on my website, I aim to present them with a breakfast item, lunch item, and dinner item. Initially, I envisioned achieving this by individually performing db.collection("recipes").findOne queries, then passing the result to an E ...

Guide to Making a Cookie Using Node's cookie-session Package

I'm currently working on a small node application and my goal is to have it create a cookie for every visitor, named 'session', which will store the session ID. However, I've been facing some challenges in getting node to generate this ...

What is the process for performing a redirection in Node JS?

I have been working on a task to redirect a page to the home page with the route '/search' upon form submission. Within my submit.html file, there is a form that utilizes the '/submit' post method to submit the form data when the submit ...

Printing a specific field from a database table with the help of the body-parser framework

My server node simply queries a database and displays the results on the browser. However, I am facing an issue where I can retrieve all records from a table, but not individual fields from the table.        I attempted to resolve this by using the ...

What is the best way to incorporate a formArray into a formGroup?

Before anything else, I want to apologize for any errors in my English. I seem to be having trouble adding an array field to a formGroup. My issue arises when attempting to use the push method to add a formArray to my rate formGroup. It appears that the ...

Using the -t or --testNamePattern in Jest will execute all tests

Currently, I have set up my testing framework using jest and ts-jest based on the guidelines provided by the ts-jest documentation. When I execute the command yarn test --listTests, I can identify the specific test file I intend to run: processNewUser.ts ...

Difficulty encountered in integrating Passport-jwt with node-jwt-simple caused authentication issues

In my current project, I am using the passport-jwt for route authentication. I have encountered some issues while creating my jwts using either node-jwt-simple or jwt-simple. It seems like the middleware for authentication in passport-jwt is not being trig ...

How to instantiate an object in Angular 4 without any parameters

Currently, I am still getting the hang of Angular 4 Framework. I encountered a problem in creating an object within a component and initializing it as a new instance of a class. Despite importing the class into the component.ts file, I keep receiving an er ...

What is the best way to guide users to different pages on the website without disrupting the socket connection?

I am looking to create a user-friendly web application utilizing socket.io and express. This website will consist of two main pages: the "Rooms" page and the individual "Room" page. The "Rooms" page allows users to input their name, create a new room, or j ...

Visibility of Input-properties in Angular 2

I am encountering an issue where a component parent is calling another component child with an input-property. Although the property is available in the child's template, it does not seem to be accessible within the constructor or OnInit functions. I ...

Various concatenated and compressed JavaScript files across multiple HTML documents within a single application

In my express.js application, I have different routes such as /home and /dashboard. For example, on the home page, I include: jquery.js, underscore.js, somemodule1.js, somemodule2.js. On the dashboard, I include: jquery.js, underscore.js, somemodule3.js, ...

Export both the enum and default function in the Typescript declaration for uuidv5

My goal is to create a Typescript Declaration for uuidv5, my first declaration for a 3rd party module. The structure of the module is unfamiliar to me, as it looks like this: function uuidToString(uuid) { } function uuidFromString(uuid) { } function cre ...

Empowering your Angular2 application with data binding

I am currently working with the following template: <table width="700"> <caption>All Users</caption> <thead> <tr> <th>name</th> <th>surname</th> < ...

How to Utilize Class Members in a Callback Function in Angular 12 with Capacitor Version 3

When I click the "Device Hardware Back Button" using Capacitor 3.0, I'm trying to navigate to the parent component with the code below. The device back button is working correctly, but I'm facing an issue where I can't access class members i ...

What is the best way to only buffer specific items from an observable source and emit the rest immediately?

In this scenario, I have a stream of numbers being emitted every second. My goal is to group these numbers into arrays for a duration of 4 seconds, except when the number emitted is divisible by 5, in which case I want it to be emitted immediately without ...

What is the best way to bring in the angular/http module?

Currently, I am creating an application in Visual Studio with the help of gulp and node. Node organizes all dependencies into a folder named node_modules. During the build process, gulp transfers these dependencies to a directory called libs within wwwroo ...

Error: The socket.io client script cannot be found when using Express + socket.io

This situation is really getting to me... even though I have a functioning version of Express + Socket.io, I can't replicate it in a new project folder with standard NPM installs. Can someone please help me figure out what I'm doing wrong...? Her ...

Issues with receiving POST requests in MERN stack application

For my first application using the MERN stack, I implemented logging of HTTP requests with "morgan". The data successfully gets sent to mongodb but the post request is stuck on "pending" for 4 minutes before failing. In my code snippet from "server.js": ...