APIDevTools / json-schema-ref-parser

Parse, Resolve, and Dereference JSON Schema $ref pointers in Node and browsers
https://apitools.dev/json-schema-ref-parser
MIT License
942 stars 226 forks source link

Exclude $id from dereferenced schemas #342

Closed edge33 closed 4 months ago

edge33 commented 4 months ago

when using $RefParser.dereference resolved referenced objects have the $id property as per the resolved schema, this can cause $id clashes using the schemas with other tools relying on multiple schemas, as per: https://github.com/nearform/openapi-transformer-toolkit/issues/179

would you consider the possibility to add an option to dereference() in order to prevent adding $id to the resolved schemas?

as an example of usage:

consider the following schemas

Post.json

{
  "title": "Post",
  "type": "object",
  "properties": {
    "postId": {
      "type": "string"
    },
    "titleTx": {
      "type": "string"
    },
    "postTx": {
      "type": "string"
    },
    "author": {
      "$ref": "User.json"
    },
    "comments": {
      "type": "array",
      "items": {
        "$ref": "Comment.json"
      }
    }
  },
  "required": [
    "postId",
    "titleTx"
  ],
  "$id": "Post.json"
}
User.json

{
  "title": "User",
  "type": "object",
  "properties": {
    "userId": {
      "type": "string"
    },
    "userNm": {
      "type": "string"
    },
    "emailAddr": {
      "type": "string"
    }
  },
  "required": [
    "userId",
    "userNm"
  ],
  "$id": "User.json"
}

The dereferenced Post schema would be:

Post.json

{
  "title": "Post",
  "type": "object",
  "properties": {
    "postId": {
      "type": "string"
    },
    "titleTx": {
      "type": "string"
    },
    "postTx": {
      "type": "string"
    },
    "author": {
      "title": "User",
      "type": "object",
      "properties": {
        "userId": {
          "type": "string"
        },
        "userNm": {
          "type": "string"
        },
        "emailAddr": {
          "type": "string"
        }
      },
      "required": ["userId", "userNm"],
      "$id": "User.json"
    },
    "comments": {
      "type": "array",
      "items": {
        "$ref": "Comment.json"
      }
    }
  },
  "required": ["postId", "titleTx"],
  "$id": "Post.json"
}

with a configuration flag like dereference({removeResolvedIds:false}) the output schema in the example would not have the "$id": "User.json" in the author property

jonluca commented 4 months ago

Cant you just recursively iterate over the properties and remove $id? It is valid JSON schema to include it so I dont think it's the responsibility of this library to provide that option

simoneb commented 4 months ago

We had already solved it on our side, as you can see from the linked issue, we just thought it may make sense to include the feature directly in the library, so we took the time to create the issue.