json-schema-ref-parser icon indicating copy to clipboard operation
json-schema-ref-parser copied to clipboard

merge the resolved value and the original reference

Open wanghongcheng0302 opened this issue 2 years ago • 2 comments

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 avatar Apr 10 '23 09:04 wanghongcheng0302

Fixed result

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

wanghongcheng0302 avatar Apr 11 '23 01:04 wanghongcheng0302

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

udamir avatar Dec 22 '23 06:12 udamir

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

jonluca avatar Mar 06 '24 01:03 jonluca