joao
joao

Reputation: 451

Use interface as a swagger schema - NestJS DTO

I have the following code:

import { IsNotEmpty, IsArray, ArrayMinSize } from 'class-validator';
import { ApiProperty } from '@nestjs/swagger';

export class PublishDto {
  @IsNotEmpty()
  @IsArray()
  @ArrayMinSize(1)
  @ApiProperty({
    type: [Product]
  })
  products: Product[];
}

interface Product {
  id: string;
  title: string;
  sku: string;
  stock: number;
  description: string;
  shortDescription: string;
  imagesUrl: string[];
  price: number;
  department: string;
  category: string;
  brand: string;
  keywords: string[];
  isActive: boolean;
}

enter image description here

I'm trying to put the interface Product as a schema on swagger, but it's not working, I am getting an error. Any idea?

Upvotes: 10

Views: 10633

Answers (1)

Jesse Carter
Jesse Carter

Reputation: 21147

The type property is expecting a value that is available at runtime, for example an actual Class or the Javascript String type. Interfaces exist only at compile time and so they aren't valid to be passed in this way.

You'll have to convert it to a Class if you want to pass it manually otherwise you could take a look at using the NestJS Swagger compiler plugin which uses some cool compile-time magic to automatically try and figure some of this stuff out for you

Upvotes: 11

Related Questions