简体   繁体   中英

NestJS Global Prefix and parameters

We define a prefix that we almost to all urls let's say "companyName". To prevent it we used the Global Prefix in main.ts

app.setGlobalPrefix(':companyName/');

There is any way to grab it as a global variable?

We thought about developing a Middleware but we don't know if a global variable will stay with the same value for all requests or the value will be changed by other requests.

No, storing it in as global variable will not work. The global variable is unique and will be shared by all your requests, so as you guessed other requests might change its value.

And even if it would work, the companyName is the context of your request not of your app. Global variable should be constant values. Like database URI or whatever values that should not change after startup but should be accessible across the app.

The easiest way to do what you want to do is to read the value from the URI in the controller and pass this value to your business service. Like this each request will have is own context, independent from other requests, reducing the risk of side effects.

In case you don't know how to retrieve the value, here is a small example.

To retrieve the value it's quite simple. Do like what you would do with a classic http param. You can find some basic examples in the doc https://docs.nestjs.com/controllers#route-parameters

As long as you can access the URI, you can retrieve this value.

In a controller, for example, you can get it through the @Param annotation as follow:

@Get('someroute')
yourRoute(
  @Param('companyName') companyName: string
): {
  *do something*
}

You can also access it in any kind of middleware by reading directly from the request.

For example, in a guard, you can do something like this:

async canActivate(context: ExecutionContext): Promise<boolean> {
  const request: Request = context.switchToHttp().getRequest();
  const companyName = request.params['companyName']
  *do something*
}

Hope this answer your question.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM