Skip to content

$ref and $id implementation #1

Closed
@Eomm

Description

@Eomm

From the docs, it is not clear which version of the json schema standard this library is supported.

From a quick test, I think we have few use cases that are not covered:

Therefore, "$id" MUST NOT contain a non-empty fragment, and SHOULD NOT contain an empty fragment. The absolute-URI form MUST be considered the canonical URI, regardless of the presence or absence of an empty fragment. An empty fragment is currently allowed because older meta-schemas have an empty fragment in their $id (or previously, id). A future draft may outright forbid even empty fragments in "$id".

From spec: https://json-schema.org/draft/2020-12/json-schema-core#name-the-id-keyword

This example should behave in a different way:

const assert = require('node:assert')
const { RefResolver } = require('json-schema-ref-resolver')


const inputSchema = {
  "$id": "http://example.com/root.json",
  "definitions": {
    "A": { "$id": "#foo" },
    "B": {
      "$id": "other.json",
      "definitions": {
        "X": { "$id": "#bar", type: 'string' },
        "Y": { "$id": "t/inner.json" }
      }
    },
    "C": {
      "$id": "urn:uuid:ee564b8a-7a87-4125-8c96-e9f123d6766f",
      type: 'object',
    }
  }
}

const addresSchema = {
  $id: 'relativeAddress', // Note: prefer always absolute URI like: http://mysite.com
  type: 'object',
  properties: {
    zip: { $ref: 'urn:uuid:ee564b8a-7a87-4125-8c96-e9f123d6766f' },
    city: { $ref: 'http://example.com/root.json#foo' }, // ❗️ should work
// city2: { $ref: '#foo' } // wrong syntax, ❗️ should say ref not found. triggers TypeError: Cannot read properties of null (reading '$ref')  }
}


const refResolver = new RefResolver()
refResolver.addSchema(inputSchema)
refResolver.addSchema(addresSchema)

refResolver.derefSchema('relativeAddress')
const derefSourceSchema = refResolver.getDerefSchema('relativeAddress')
console.log(derefSourceSchema)

I wrote almost the same lib: https://github.com/Eomm/json-schema-resolver
It is used in fastify-swagger, and we can get the tests to have a wider suite.
The code there can be optimized if we want to use it.

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