Max Koretskyi
Max Koretskyi

Reputation: 105517

Redirect request not specifying API version to the default version

We define versioning like this:

  app.enableVersioning({
    type: VersioningType.URI,
    defaultVersion: "1"
  });

It adds gloable prefix v${version} to routes, and is configurable. So client must send request like this api/v1/users. What I want is to not send v1 from the client for most requests and make nest automatically redirect from api/users to api/v${defaultApiVersion}/users.

How can I achieve this?

Upvotes: 1

Views: 417

Answers (1)

Thierry Falvo
Thierry Falvo

Reputation: 6290

For that, you can use VERSION_NEUTRAL to mark default endpoint version :

Some controllers or routes may not care about the version and would have the same functionality regardless of the version. To accommodate this, the version can be set to VERSION_NEUTRAL symbol.

An incoming request will be mapped to a VERSION_NEUTRAL controller or route regardless of the version sent in the request in addition to if the request does not contain a version at all.

So, for example, here, route with v1 or without version will both be processed by getMessageV1 :

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

  @Version(['1', VERSION_NEUTRAL])
  @Get()
  getMessageV1(): string {
    return 'Message V1';
  }

  @Version('2')
  @Get()
  getMessageV2(): string {
    return 'Message V2';
  }
}

More details on official docs.

Upvotes: 1

Related Questions