get-graphql-from-jsonschema
get-graphql-from-jsonschema copied to clipboard
Missing support for field "$ref" in schemas
I was hitting some annoyances, and one big stopper, from the fact that this library doesn't yet support the "$ref" field in schemas, so I went ahead and added basic support for it.
Usage:
// At some point (can be before, after, or in the same loop), add the graphql types referenced by the "$ref" fields. Example:
const schemasUsedForRefs = [...];
for (const schema of schemasUsedForRefs) {
const {typeDefinitions} = getGraphqlSchemaFromJsonSchema({ rootName: schema.$id, schema });
addTypesToGraphQL(typeDefinitions);
}
// For schemas with "$ref" fields, pass a "refToTypeName" function during graphql type generation.
// This allows the library to resolve the "$ref" names to graphql type names. (will error otherwise)
const schemasThatUseRefs = [...];
for (const schema of schemasThatUseRefs) {
const {typeDefinitions} = getGraphqlSchemaFromJsonSchema({
rootName: schema.$id,
schema,
refToTypeName: refName=>{
// Can add custom logic here, depending on the naming used for generating the schemas' graphql types.
return `${refName}T0`;
},
});
addTypesToGraphQL(typeDefinitions);
}
And here are the code changes made, for adding support for both enum
and $ref
: https://github.com/thenativeweb/get-graphql-from-jsonschema/compare/main...Venryx:...
As mentioned in your earlier comment, there is some work still needed to be done for this (for example, adding tests and documentation).
I'll create a PR for it once a final design has been decided on, and I have time to add unit tests and such.
I am continuing the discussion from the other issues and quoting relevant parts.
Why would it not work for circular references? The library does not actually "resolve" the graphql types that are referenced, it merely provides a way for the user to say "Okay, here is the graphql type name that we'll be using for this json-schema name; I'll provide it to my GraphQL server myself, and you can just trust that it'll be there at runtime."
You are right. I only see the drawback that developers need to know the resulting names of the types before converting them. Since the names are currently deterministic, this is not really an issue. So yeah, the approach should work for basically all use-cases and I find it quite elegant :)