Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nestjs/swagger: Complex Objects

Tags:

swagger

nestjs

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": {}
}
like image 996
Alexandre Fradette Avatar asked Jun 18 '18 16:06

Alexandre Fradette


People also ask

What is nestjs and how to use it?

Nestjs, not like any other nodejs frameworks, has many handy tools, libraries and features that let us write our programs following clean code and scalable architecture. In this article we’ll find out how to use swagger for documentation of our application, and also know the best practices for module creation.

Is it possible to serialise parameters to a string in Swagger?

So I changed the things you mentioned, but Swagger doesn't seem to be able to serialise the parameters into a query string. The resulting URL is query?size=10&start=0&filters=%5Bobject%20Object%5D

What is the difference between “providers” and “exports” in nestjs?

“providers” is an array of classes that are used in our module. On the compiling stage nestjs will create objects automatically with resolving constructor dependencies. “exports” - in this section you can specify providers classes that can be used in providers other modules.


1 Answers

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.

like image 188
Chau Tran Avatar answered Oct 10 '22 07:10

Chau Tran