#Reading version in controllers

12 messages ยท Page 1 of 1 (latest)

noble silo
#

Hiya! ๐Ÿ‘‹

I have a case where a controller method (endpoint) can have multiple versions. During the controller logic I will need to perform an action based on which version is in use. Anyone knows if its possible to read the version somehow?

Example:

class AnimalController {
  @Version(['dog', 'cat'])
  @Post()
  createAnimal() {
    if (version === 'cat') {
      // Meow
    }
  }
}
ember adder
# noble silo Hiya! ๐Ÿ‘‹ I have a case where a controller method (endpoint) can have multiple ...
import { SetMetadata } from '@nestjs/common';

export const VERSION_METADATA_KEY = 'versions';

export const Version = (versions: string[]) =>
  SetMetadata(VERSION_METADATA_KEY, versions);

class AnimalController {
  @Version(['dog', 'cat'])
  @Post()
  createAnimal() {
    const versions = Reflect.getMetadata(
      VERSION_METADATA_KEY, // <-- the key we defined earlier above
      AnimalController.prototype.createAnimal, // <-- current method
    );

    console.log(versions); // ['dog', 'cat']

    if (versions.includes('cat') {
      // Meow? :)
    }
  }
}
frank harness
#

I believe OP's want to use the versioning feature from nestjs, not its own decorator. Right, @noble silo ?

ember adder
#

yeah most likely, checking an static array doesn't make sense, mb CB_pika_think

frank harness
#

and there's no abstraction to retrieve which version is being invoked

noble silo
#

Exactly ๐Ÿ™‚ Essentially I have a method that will be used in two cases, and instead of creating a method for each case, I was hoping to just use the same and check on the version used.. I could have it as a route param also, but since its a spec implementation, it has to be part of the version and not just a route param (which would have been alot easier :D)

frank harness
# noble silo Exactly ๐Ÿ™‚ Essentially I have a method that will be used in two cases, and inste...

you can open a feature request at https://github.com/nestjs/nest
that sounds reasonable since versioning is a "first-class citizen" in nest

GitHub

A progressive Node.js framework for building efficient, scalable, and enterprise-grade server-side applications with TypeScript/JavaScript ๐Ÿš€ - GitHub - nestjs/nest: A progressive Node.js framework ...

noble silo
#

Yeah I also think it would be a good feature to have.. I'll set up a request when back at the job tomorrow ๐Ÿ™‚ Thanks!

meager forge
frank harness
#

or maybe as a new parameter decorator
but I'd like to avoid adding new decorators

meager forge