Skip to content

Fix repository-json-schema to handle circular references #2628

@bajtos

Description

@bajtos

Description / Steps to reproduce / Feature proposal

Consider the following test case:

it('handles circular references', () => {
  @model()
  class Category {
    @property.array(() => Product)
    products?: Product[];
  }

  @model()
  class Product {
    @property(() => Category)
    category?: Category;
  }

  const schema = modelToJsonSchema(Category);
  expect(schema).to.deepEqual({
    title: 'Category',
    properties: {
      products: {
        type: 'array',
        items: {$ref: '#/definitions/Product'},
      },
    },
    definitions: {
      Product: {
        title: 'Product',
        properties: {
          category: {
            $ref: '#/definitions/Category',
          },
        },
      },
    },
  });
});

Please note this test case is synthetic and does not represent the actual design we will use for relation navigational properties.

Current Behavior

The test fails with a stack-overflow error.

       handles circular references:
     RangeError: Maximum call stack size exceeded
      at RegExp.test (<anonymous>)
      at isTypeResolver (/Users/bajtos/src/loopback/next/packages/repository/src/type-resolver.ts:44:16)
      at Object.resolveType (/Users/bajtos/src/loopback/next/packages/repository/src/type-resolver.ts:88:10)
      at metaToJsonProperty (src/build-schema.ts:148:24)
      at modelToJsonSchema (src/build-schema.ts:241:28)
      at getJsonSchema (src/build-schema.ts:38:23)
      at modelToJsonSchema (src/build-schema.ts:263:24)
      at getJsonSchema (src/build-schema.ts:38:23)
      at modelToJsonSchema (src/build-schema.ts:263:24)
      at getJsonSchema (src/build-schema.ts:38:23)
      at ` (src/build-schema.ts:263:24)
      ...

Expected Behavior

The tests passes.

Additional information

See the spike #2592 and the commit 2256435 for more details.

The idea is to introduce a new options argument to getJsonSchema and modelToJsonSchema functions, this argument will expect the following properties to begin with:

export interface JsonSchemaOptions {
  visited?: {[key: string]: JSONSchema};
}

Acceptance criteria

  • Make the changes necessary to make the above test pass
  • Add additional test coverage at unit-test and integration level as necessary
  • Update API documentation

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions