Skip to content

Instantly share code, notes, and snippets.

@serefyarar
Created May 17, 2024 16:36
Show Gist options
  • Save serefyarar/1166c645e13f3c18d58a9f6c05f479ae to your computer and use it in GitHub Desktop.
Save serefyarar/1166c645e13f3c18d58a9f6c05f479ae to your computer and use it in GitHub Desktop.
JSON Schema to GraphQL Fragment
//Thank you ChatGPT
function jsonSchemaToGraphQLFragment(schema, typeName, setPrefix = false) {
// Helper function to resolve $ref references within the schema
function resolveRef(ref, defs) {
const refPath = ref.replace(/^#\/\$defs\//, '');
return defs[refPath];
}
// Helper function to process each field in the schema
function processField(fieldName, fieldSchema, defs, indentLevel, isParent = false) {
const indent = ' '.repeat(indentLevel);
const prefixedFieldName = isParent && setPrefix ? `${typeName}_${fieldName} : ${fieldName}` : fieldName;
if (fieldSchema.$ref) {
// Resolve the reference and process the resolved schema
const resolvedSchema = resolveRef(fieldSchema.$ref, defs);
return processField(prefixedFieldName, resolvedSchema, defs, indentLevel, isParent);
}
if (fieldSchema.type === 'object' && fieldSchema.properties) {
// Process nested object fields
const nestedFields = Object.entries(fieldSchema.properties)
.map(([key, value]) => processField(key, value, defs, indentLevel + 1))
.join('\n');
return `${indent}${prefixedFieldName} {\n${nestedFields}\n${indent}}`;
}
if (fieldSchema.type === 'array' && fieldSchema.items) {
// Process array fields
const arrayFields = processField(prefixedFieldName, fieldSchema.items, defs, indentLevel);
return arrayFields;
}
// Treat as scalar field
return `${indent}${prefixedFieldName}`;
}
// Main function to process the schema
const fields = Object.entries(schema.properties)
.map(([key, value]) => processField(key, value, schema.$defs || {}, 1, true))
.join('\n');
return `
... on ${typeName} {
${fields}
}`.trim();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment