I am using the GraphQL types module to create my GraphQL schema by looping over a bunch of JSON Schemas. I appear to be stuck on a problem when it comes to referencing to other Types. How can I create a type from a JSON Schema, and reference to itself or other types before they are created?
All my types can be references at a path. The file in the path is responsible for creating the schema dynamically for the Type:
import { JSONSchema } from "./index"
import { createGraphQLType } from "../../graphql";
export default createGraphQLType(JSONSchema, "Query")
The createGraphQLType
function is quite simple, it just takes the types in the JSONSchema and switches it to a GraphQL Type by using propertiesToFields()
.
export default (schema: JSONSchema4, resolverType: string) => {
const resolvers = propertiesToFields(schema.properties, resolverType);
return new GraphQLObjectType({
name: schema.title,
description: schema.description,
fields: () => ({...resolvers})
});
};
However when it comes across a reference to another type, it returns a promise for the path to the GraphQL Type. The problem is that this returns a promise.
const dir = process.env.PWD + "/dist/models";
export default function(name: string): Promise<GraphQLType> {
try {
return import(dir + "/" + name);
} catch (err) {
throw err;
}
};
This in turn throws an error when I try to run the schema:
(node:74096) UnhandledPromiseRejectionWarning: Error: Schema must contain uniquely named types but contains multiple types named "undefined". at typeMapReducer (/Users/vemundeldegard/salire/data-api/node_modules/graphql/type/schema.js:262:13) at typeMapReducer (/Users/vemundeldegard/salire/data-api/node_modules/graphql/type/schema.js:286:20) at typeMapReducer (/Users/vemundeldegard/salire/data-api/node_modules/graphql/type/schema.js:286:20) at Array.reduce () at new GraphQLSchema (/Users/vemundeldegard/salire/data-api/node_modules/graphql/type/schema.js:145:28) at /Users/vemundeldegard/salire/data-api/dist/graphql/index.js:34:18 at Generator.next () at fulfilled (/Users/vemundeldegard/salire/data-api/dist/graphql/index.js:5:58)