Search code examples
graphqlgraphql-java

GraphQL Schema Definition Language support in graphql-java


Hi I'm new to graphql specially graphql-java .

Is there any possible way to use GraphQL Schema Definition Language support in graphql-java? If yes then how it is possible?


Solution

  • Yes, it is possible since release 3.0.0.

    schema {
        query: QueryType
    }
    
    type QueryType {
        hero(episode: Episode): Character
        human(id : String) : Human
        droid(id: ID!): Droid
    }
    

    You can convert an the following IDL-File (starWarsSchema.graphqls) to an executable schema like this:

    SchemaParser schemaParser = new SchemaParser();
    SchemaGenerator schemaGenerator = new SchemaGenerator();
    
    File schemaFile = loadSchema("starWarsSchema.graphqls");
    
    TypeDefinitionRegistry typeRegistry = schemaParser.parse(schemaFile);
    RuntimeWiring wiring = buildRuntimeWiring();
    GraphQLSchema graphQLSchema = schemaGenerator.makeExecutableSchema(typeRegistry, wiring);
    

    Also you have to implement the buildRuntime function to wire your static schema with the resolvers.

    RuntimeWiring buildRuntimeWiring() {
        return RuntimeWiring.newRuntimeWiring()
                .scalar(CustomScalar)
                .type("QueryType", typeWiring -> typeWiring
                        .dataFetcher("hero", new StaticDataFetcher(StarWarsData.getArtoo()))
                        .dataFetcher("human", StarWarsData.getHumanDataFetcher())
                        .dataFetcher("droid", StarWarsData.getDroidDataFetcher())
                )
                .build();
    }
    

    A more detailed example you can find in the graphql-java documentation.