Alexandre Fradette
Alexandre Fradette

Reputation: 372

Nestjs/swagger: Complex Objects

I was wondering if there's a way to support complex objects for Nestjs/swagger. I just finished the migration and I am now working on the swagger documentation. A lot of my requests return complex objects and I'm wondering if there's an easier way. Example:

class Foobar{
  prop1: {
    subprop1: {
      subsub1: string;
    };
  };
}

Becomes:

class SubSub{
  @ApiModelProperty()
  subsub1: string;
}
class SubProp{
  @ApiModelProperty()
  subporp1: SubSub;
}
class Foobar {
  @ApiModelProperty()
  prop1: SubProp;
}

If I do this:

class Foobar{
  @ApiModelProperty()
  prop1: {
    subprop1: {
      subsub1: string;
    };
  };
}

I get this in swagger:

{
  "prop1": {}
}

Upvotes: 20

Views: 39822

Answers (2)

Capka3m
Capka3m

Reputation: 81

class SubSub {
  @ApiProperty()
  subsub1: string;
}

class SubProp {
  @ApiProperty({ type: SubSub })
  subporp1: SubSub;
}

or if Array

class SubProp {
  @ApiProperty({ isArray: true,  type: SubSub })
  subporp1: SubSub[];
  //or subporp1: [SubSub];
}

Upvotes: 8

Chau Tran
Chau Tran

Reputation: 5108

UPDATE 04/2020: ApiModelProperty now has been changed to ApiProperty

    class SubSub{
      @ApiProperty()
      subsub1: string;
    }

    class SubProp{
      @ApiProperty({ type: SubSub })
      subporp1: SubSub;
    }

    class Foobar {
      @ApiProperty({ type: () => SubProp })
      prop1: SubProp;
    }

In the last ApiProperty, I used "Lazy Evaluated Function" syntax. This is to prevent Circular Dependency problem. Thought I'd add it in there.


class SubSub{
  @ApiModelProperty()
  subsub1: string;
}

class SubProp{
  @ApiModelProperty({ type: SubSub })
  subporp1: SubSub;
}

class Foobar {
  @ApiModelProperty({ type: SubProp })
  prop1: SubProp;
}

The @ApiModelProperty takes in an option object where you can specify the type if it's a complex object.

Upvotes: 70

Related Questions