Skip to content

Instantly share code, notes, and snippets.

@arjan
Created March 5, 2020 08:19
Show Gist options
  • Save arjan/bf90aa09808d4aa0be15f798c900d6fc to your computer and use it in GitHub Desktop.
Save arjan/bf90aa09808d4aa0be15f798c900d6fc to your computer and use it in GitHub Desktop.
Pre-process RJSF ui:schema to resolve references
// Pre-process RJSF ui:schema to resolve references
import cloneDeep from 'lodash/cloneDeep'
function traverse(object, definitions) {
for (let k of Object.keys(object)) {
const v = object[k]
if (v === null) {
continue
}
if (Array.isArray(v)) {
v.forEach(item => traverse(item, definitions))
continue
}
if (typeof v === 'object') {
if (v.$ref && v.$ref.startsWith('#/definitions/')) {
const k = v.$ref.substr(14)
if (definitions[k]) {
delete v.$ref
Object.entries(definitions[k]).forEach(([k, v1]) => { v[k] = v1 })
}
} else {
traverse(v, definitions)
}
}
}
}
export function resolveUiSchemaReferences(input) {
let { definitions, ...schema } = input
schema = cloneDeep(schema)
if (typeof definitions === 'object') {
traverse(schema, definitions)
}
return schema
}
@gordielachance
Copy link

gordielachance commented Jan 3, 2023

Thanks, but does not work if you use $ref in the definitions themselves... :)
This works but I guess this is not really clean :

if (typeof $defs === 'object'){
  //replace $ref within the definitions theirselves
  $defs = cloneDeep($defs);
  traverse($defs,$defs);

  //replace $ref within the schema
  schema = cloneDeep(schema);
  traverse(schema, $defs)
}

@gordielachance
Copy link

Maybe that this tool is better ?
But I can't get it working in my React app.
https://github.com/APIDevTools/json-schema-ref-parser

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment