What is the best way to handle a global path parameter in a Nest.js application?

Currently, I am in the process of constructing a rest API for a fully multi-tenant system using a single database and application. To achieve this, I have chosen NestJS as my framework of choice. My goal is to structure all modules based on the :tenantID that I provide at the root location of the application.

For instance, if I have modules such as users and conversations, I envision the endpoints to appear like this:

app_url/:tenantID/users app_url/:tenantID/conversations

Despite my efforts, I have not been able to find any guidance on how to implement this specific feature.

Answer №1

If you want to easily include the global parameter in all controllers' routes, you can do it like this:

app.controller.ts:

import { Controller, Get, Param } from '@nestjs/common';
import { AppService } from './app.service';

@Controller(':account')
export class AppController {
    constructor(private readonly appService: AppService) {}

    @Get()
    getHello(@Param('account') account: string): string {
        console.log(account)
        return this.appService.getHello();
    }
}

users.controller.ts:

import { Controller, Get, Param } from '@nestjs/common';

@Controller(':account/users')
export class UsersController {
    @Get()
    getUsers(@Param('account') account: string) {
        console.log(`Account ${account} has the following users:`);
        return true;
    }
}

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

Exploring the functionality of this TypeScript code: What's the distinction between { [key: string]: string }[] and { prop1: string, prop2: string }[]

Below is the code I am currently working with: get tags(): { [key: string]: string }[] { let tags: { [key: string]: string }[] = []; if(this.tags) { Object.keys(this.tags).forEach(x => { tags.push({ prop1: this.tags[x], prop2: g ...

"Encountering Devextreme Reactive Errors while navigating on the main client

Attempting to integrate Devextreme with Material Ui in my Typescript React app has been a challenge. Despite following the steps outlined in this documentation and installing all necessary packages, I am encountering issues. I have also installed Material ...

Tips for efficiently utilizing Hooks with React Context:

I am currently working on my application and utilizing React Context with the setState function. const userContext = React.createContext([{ user: {} }, () => {}]); const userHook = useState({ user: {} }); <userContext.Provider value={userHook}> / ...

React form submissions are not saving the state

I currently have dynamic components rendered from the server side, including a submit button component. The issue I am facing is that when I submit the form, the state reverts to its initial values instead of retaining the updated values set by child compo ...

How to use ngModel directive in Angular to select/unselect dynamically generated checkboxes and retrieve their values

Currently, I am working with a dataset retrieved from an API and dynamically creating checkboxes in my HTML page using the DataView component from PrimeNG. My objective is to implement a feature where users can select or deselect all checkboxes with a cli ...

Encountering an error of undefined upon submission of a form while utilizing ng

Sorry if this question has been asked before, but I've searched extensively online and still can't find a solution. I'm new to Angular and TypeScript and I may be overlooking something simple, but I can't get it to work. Any help would ...

Ensuring accurate properties are sent to popup notifications

As a newcomer to a React & ASP.NET project, I am facing a challenge in displaying upload status notifications. The task may seem simple, but I need help in figuring out how to create popup notifications that indicate which files have been successfully uplo ...

The authService is facing dependency resolution issues with the jwtService, causing a roadblock in the application's functionality

I'm puzzled by the error message I received: [Nest] 1276 - 25/04/2024 19:39:31 ERROR [ExceptionHandler] Nest can't resolve dependencies of the AuthService (?, JwtService). Please make sure that the argument UsersService at index [0] is availab ...

Using TypeScript: Union Types for Enum Key Values

Here's the code in the TS playground too, click here. Get the Enum key values as union types (for function parameter) I have managed to achieve this with the animals object by using key in to extract the key as the enum ANIMALS value. However, I am s ...

Angular 2, the change event is not triggering when a bootstrap checkbox is clicked

Encountering an issue, the (change) function is not triggering in a specific checkbox. <input [(ngModel)]="driver.glasses" name="glasses" type="checkbox" class="make-switch" (change)="changeFunction()" data-on-color="primary" data-off-color="info"&g ...

Encountering an issue with MUI Props: "Must provide 4 to 5 type arguments."

I'm attempting to use a custom component and pass in AutocompleteProps as a prop, all while utilizing typescript. Here's my current setup: type Props = { autoCompleteProps?: AutocompleteProps<T> label: string loading?: boolean } cons ...

Display Material Popup in Angular before user leaves the page

My goal is to display an Angular Material Dialog Box (Popup window) when the user clicks the Chrome Window Close button. The Dialog modal should prompt the user if they want to save changes or cancel. However, the modal only appears for a brief moment and ...

Tips for implementing a multi-layered accumulation system with the reduce function

Consider the following scenario: const elements = [ { fieldA: true }, { fieldB: true }, { fieldA: true, fieldB: true }, { fieldB: true }, { fieldB: true }, ]; const [withFieldA, withoutFieldA] = elements.reduce( (acc, entry) => ...

Organized modules within an NPM package

I am looking to develop an NPM package that organizes imports into modules for better organization. Currently, when I integrate my NPM package into other projects, the import statement looks like this: import { myFunction1, myFunction2 } from 'my-pac ...

Utilizing React Typescript to Efficiently Manage Multiple Checkboxes within a List

I'm working on a scenario where I have to manage multiple checkboxes in a list Only one checkbox can be selected at a time For example, if I toggle on Checkbox 1 and then click on Checkbox 2 - I want to automatically toggle off Checkbox 1 as I toggl ...

Iterating through elements within the ng-content directive in Angular using *ngFor

Is it possible to iterate through specific elements in ng-content and assign a different CSS class to each element? Currently, I am passing a parameter to enumerate child elements, but I would like to achieve this without using numbers. Here is an example ...

Replace Formik with useFormik to streamline your code

I have implemented Formik/Yup for validation on a page that triggers a GraphQL mutation. The code is functioning as expected: export default function RemoveUserPage() { const [isSubmitted, setIsSubmitted] = useState(false); const [isRemoved ,setIsRemo ...

Utilizing the backtick operator for string interpolation allows for dynamic value insertion

Greetings! Currently, I am delving into the world of Angular 2 and have stumbled upon some interesting discoveries. To enhance my knowledge of TypeScript, I decided to utilize the ScratchJS extension on the Chrome browser. During this exploration, I experi ...

Expect a reply within the loop

One of my endpoints takes some time to generate data, and I have another endpoint to retrieve that generated data. I make the initial call using await, extract the ID from the response, and then keep calling the second endpoint until the status is not "Suc ...

The error message "Property '$store' is not defined on type 'ComponentPublicInstance' when using Vuex 4 with TypeScript" indicates that the property '$store' is not recognized

I'm currently working on a project that involves using TypeScript and Vue with Vuex. I've encountered an error in VSCode that says: Property '$store' does not exist on type 'ComponentPublicInstance<{}, {}, {}, { errors(): any; } ...