Skip to content

Error when resolving nested schema refs by id ({"$ref": "#foo"}) #350

@SleepWalker

Description

@SleepWalker

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure it has not already been reported

Fastify version

3.20.2

Plugin version

No response

Node.js version

v14.16.0

Operating system

Linux

Operating system version (i.e. 20.04, 11.3, 10)

Ubuntu 20.04.2

Description

refFinder fails to find a $ref by $id (docs), when the schema is nested, e.g.:

{
  "title": "Example Schema",
  "type": "object",
  "properties": {
    "nested": {
      "type": "object",
      "properties": {
        "firstName": {
          "$ref": "#foo"
        },
        "lastName": {
          "$ref": "#foo"
        }
      }
    }
  },
  "definitions": {
    "foo": {
      "$id": "#foo",
      "type": "string"
    }
  }
}

There are actually two errors (source):

  • if there is no externalSchema, you'll get TypeError: Cannot convert undefined or null to object when executing for (var key of Object.keys(externalSchema)) {
  • if externalSchema is specified, refFinder will fail to dereference $ref and a property will end up resolved to undefined which will trigger TypeError: Cannot read property 'type' of undefined on the later stages in buildCode

Looks like refFinder should look up for definitions starting from root instead of schema in the same way as it done for processing of #/definitions/foo refs.

Steps to Reproduce

const fastJson = require('fast-json-stringify');
const stringify = fastJson({
  title: 'Example Schema',
  type: 'object',
  properties: {
    firstName: { $ref: '#foo' },
    lastName: { $ref: '#foo' },
    nested: {
      type: 'object',
      properties: {
        firstName: { $ref: '#foo' },
        lastName: { $ref: '#foo' },
      },
    },
  },
  definitions: {
    foo: {
      $id: '#foo',
      type: 'string',
    },
  },
});

console.log(
  stringify({
    firstName: 'Matteo',
    lastName: 'Collina',
    nested: {
      firstName: 'Matteo',
      lastName: 'Collina',
    },
  }),
);

Expected Behavior

The nested $ref should be resolved. Here is an example of schema validation: https://www.jsonschemavalidator.net/s/sMCUkqfP

Metadata

Metadata

Assignees

No one assigned

    Labels

    good first issueGood for newcomerssemver-minorIssue or PR that should land as semver minor

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions