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

Calling dereference mutates input schema, while example does not indicate this

Open Swiftwork opened this issue 3 years ago • 3 comments

The example section seems to indicate that a new schema object with be created with the dereferenced values, but in reality, it mutates mySchema as well. Either the dereference command shouldn't mutate the original object or the example should be updated to reflect reality.

https://github.com/APIDevTools/json-schema-ref-parser#example

try {
  let schema = await $RefParser.dereference(mySchema);
  console.log(schema.definitions.person.properties.firstName);
}
catch(err) {
  console.error(err);
}

Swiftwork avatar Feb 24 '22 16:02 Swiftwork

Could you send a PR with a failing test showing the mutation happening? Then it will be much easier for somebody to take a swing at fixing it.

philsturgeon avatar Feb 28 '22 12:02 philsturgeon

Hi @philsturgeon, thanks for the suggestion. I put together a codepen example https://codesandbox.io/s/node-playground-forked-k4vvz9?file=/src/index.js to demonstrate what is happening as this was easier. What this issue is really referring to is that:

let schema = await $RefParser.dereference(mySchema);
// and
await $RefParser.dereference(mySchema);

Both are performing the same operation, mutating the original object mySchema, the only difference in the first example being that mySchema is also aliased to schema. In my opinion, mutation is harder to understand from a coding perspective and can cause some side effects, so it is better to avoid it. But if that's not possible or easily achieved, then the documentation should be clear :). If no code changes are made then the example should probably be updated to:

try {
  await $RefParser.dereference(schema);
  console.log(schema.definitions.person.properties.firstName);
}
catch(err) {
  console.error(err);
}

Swiftwork avatar Feb 28 '22 15:02 Swiftwork

I stumbled upon the same thing and indeed it'd be useful if the documentation indicated that the input schema is mutated or if the mutation didn't happen in the first place.

giorgosera avatar Apr 04 '23 16:04 giorgosera

Great idea, included this as a flag in the latest version to preserve the historical behavior. I also updated the readme to better reflect the mutation in place

jonluca avatar Mar 06 '24 07:03 jonluca