Skip to content

maxSampleDepth sometimes causes null in sample data #37

@ilittle-cnri

Description

@ilittle-cnri

maxSampleDepth doesn't always traverse schemas correctly. In some cases, it produces null in the example, instead of the actual type.

Context

When the example shows null instead of the correct type, it is confusing to users of the API documentation

Current Behavior

Given this schema:

{
  "$schema": "https://json-schema.org/draft-07/schema#",
  "type": "object",
  "required": [
    "someObjects"
  ],
  "properties": {
    "someObjects": {
      "type": "array",
      "items": {
        "type": "object",
        "properties": {
          "someStrings": {
            "type": "array",
            "items": {
              "type": "string"
            }
          }
        }
      }
    }
  }
}

Invoking the sampler like this:

const sample = JSONSchemaSampler.sample(schema, {
    maxSampleDepth: 4
});

Produces:

{
  "someObjects": [
    {
      "someStrings": [
        null
      ]
    }
  ]
}

Expected Behavior

I would expect it to produce an example like this:

{
  "someObjects": [
    {
      "someStrings": [
        "string"
      ]
    }
  ]
}

This example is produced if maxSampleDepth is greater than 4.

Possible Workaround/Solution

As a workaround, you can set maxSampleDepth to a higher number. It defaults to 15, but I ran into this because when its used in @stoplight/elements, elements happens to set the depth to 4. Patching my version of the elements web component resolved the issue there.

Steps to Reproduce

  1. Run this javascript. Vary the maxSampleDepth to observe the bug
const JSONSchemaSampler = require('@stoplight/json-schema-sampler');

const schema = {
    "$schema": "https://json-schema.org/draft-07/schema#",
    "type": "object",
    "required": [
        "someObjects"
    ],
    "properties": {
        "someObjects": {
            "type": "array",
            "items": {
                "type": "object",
                "properties": {
                    "someStrings": {
                        "type": "array",
                        "items": {
                            "type": "string"
                        }
                    }
                }
            }
        }
    }
};

const sample = JSONSchemaSampler.sample(schema, {
    maxSampleDepth: 4
});

console.log(JSON.stringify(sample, null, 2));

Environment

  • Version used: Not sure. Whatever comes with @stoplight/elements 7.7.5
  • Environment name and version: Node 16.16.0
  • Operating System and version: MacOS 12.6.1

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions