Search code examples
loopbackjsloopback4

Remove nested relations from API explorer (swagger)


I have Application model with following relation:

  @belongsTo(() => Ido)
  idoId: string;


export interface ApplicationRelations {
  ido?: IdoWithRelations;
}

export type ApplicationWithRelations = Application & ApplicationRelations;

Application repository looks like this:

  export class ApplicationRepository extends DefaultCrudRepository<
  Application,
  typeof Application.prototype.id,
  ApplicationRelations
> {
  public readonly user: BelongsToAccessor<
    User,
    typeof Application.prototype.id
  >;

  constructor(
    @inject('datasources.db') dataSource: DbDataSource,
    @repository.getter('UserRepository')
    protected userRepositoryGetter: Getter<UserRepository>,
  ) {
    super(Application, dataSource);
    this.user = this.createBelongsToAccessorFor('user', userRepositoryGetter);

    this.inclusionResolvers.delete('ido');
  }
}

And the following relation in IDO model:

 @hasMany(() => Application)
  applications: Application[];

In post /ido in swagger i am getting this example for creating:

{
  "applications": [
    {
      "status": "string",
      "createdAt": 0,
      "idoId": "string",
      "userId": "string",
      "ido": {
        "applications": [
          {
            "status": "string",
            "createdAt": 0,
            "idoId": "string",
            "userId": "string",
            "ido": {
              "applications": [
                "string"
              ],
}

Is there any ways to remove the duplicate and kind of curricular relation for ido in application from swagger? Or this doesn't really matter and i can just manually delete all fields above the first application?


Solution

  • This answer was copied over from https://github.com/loopbackio/loopback-next/discussions/8536#discussioncomment-2655375.

    OpenAPI/Swagger is at the REST layer, which means you'll need to look inside the respective REST Controller, which would have something similar to this:

    @post('...')
    function create(
      @requestBody({
          content: {
            'application/json': {
              schema: getModelSchemaRef(Application, {
                title: 'NewApplication',
                exclude: ['id'],
              }),
            },
          },
        })
    )
    

    You can modify it as such to exclude relations:

    @post('...')
    function create(
      @requestBody({
          content: {
            'application/json': {
              schema: getModelSchemaRef(Application, {
                title: 'NewApplication',
                exclude: ['id'],
    +          includeRelations: false,
              }),
            },
          },
        })
    )
    

    An alternative is to use exclude.

    More info can be found in the API docs: https://loopback.io/doc/en/lb4/apidocs.repository-json-schema.getjsonschemaref.html