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

merge the resolved value and the original reference #316

Closed wanghongcheng0302 closed 5 months ago

wanghongcheng0302 commented 1 year ago

Hi~ I have schema like this

{
  "type": "object",
  "definitions": {
    "upload": {
      "s-props": {
        "a": "a"
      }
    }
  }
}
{
  "type": "object",
  "properties": {
    "upload": {
      "$ref": "root.json#/definitions/upload",
      "s-props": {
        "b": "b"
      }
    }
  }
}

the original reference's-props replace the resolved value's-props

{
    "type": "object",
    "properties":
    {
        "upload":
        {
            "s-props":
            {
                "b": "b"
            }
        }
    }
}

this may be caused by this code

image

I think a better way is to merge the resolved value and the resolved value, rather than by replacing

this is my fix

for (const key of Object.keys(resolvedValue)) {
  if (!(key in merged)) {
    // @ts-expect-error TS(7053): Element implicitly has an 'any' type because expre... Remove this comment to see the full error message
    merged[key] = resolvedValue[key];
  } else {
    // My Fix:
    // Object.assign(merged[key], resolvedValue[key])
  }
}
wanghongcheng0302 commented 1 year ago

Fixed result

{
    "type": "object",
    "properties":
    {
        "upload":
        {
            "s-props":
            {
                "b": "b",
                "a": "a"
            }
        }
    }
}
udamir commented 8 months ago

$ref with sibling content is equal to 'allOf: [{$ref:"..."}, sibling]'. So to merge it correctly you can use allOf-merge tool

jonluca commented 5 months ago

I dont think Object.assign is a good solution, as it only works for top level properties. I'm open to using @udamir's library, but I'm not sure how to best integrate it. Calling merge({allOf[$ref, resolvedValue]}) doesnt lead to expected values