1

When using media-type-versioning, different versions of an endpoint should have the same URL and the client can set the Accept header to the desired version: e.g.

Accept: application/vnd.adventure-works.v1+json

For version 2:

Accept: application/vnd.adventure-works.v2+json

Pseudo code for controller:


    @Controller('orders')
    export class OrdersController {
    
      @Get('orders/:id')
      getOrdersV1(@Headers('Accept') acceptHeader: string) {
        // accept header must be 'application/vnd.adventure-works.v1+json'
        return {
          orderId: 1,
          orderName: 'Order 1'
        };
      }
    
      @Get('orders/:id')
      getOrdersV2(@Headers('Accept') acceptHeader: string) {
        // accept header must be 'application/vnd.adventure-works.v2+json'
        return {
          orderId: 1,
          name: 'Order 1'
        };
      }
  • How can we implement this in NestJs?
    i.e. I need to somehow tell the NestJs router that the endpoint corresponding function should only be called when the accept-header has a fixed value:
  • will this work with nestjs-swagger?

Update

found a related feature request: #3569

TmTron
  • 17,012
  • 10
  • 94
  • 142

1 Answers1

0

you may try this:

  @Get('orders/:id')
  getOrders(@Headers('Accept') acceptHeader: string) {
    //Implement a manager class say OrderManager
    OrderManager orderManager = new OrderManager(); // Better to @Inject in constructor
    switch(acceptHeader) {
        case ''application/vnd.adventure-works.v1+json'':
            return orderManager.getOrdersV1();
        case ''application/vnd.adventure-works.v2+json'':
            return orderManager.getOrdersV2();
        default:
            // throw new InvalidInputException() if needed
            break;
    }
  }
Tanmoy Bhattacharjee
  • 1,040
  • 11
  • 21
  • Well, this implementation works, but when we have only one method, how can we tell swagger (Open API) what types we return for each accept-header? i.e. which [nestjs-swagger-decorators](https://docs.nestjs.com/openapi/decorators) to use – TmTron Oct 21 '20 at 06:20