|
| 1 | +package com.graphqljava.defer; |
| 2 | + |
| 3 | +import com.google.common.base.Charsets; |
| 4 | +import com.google.common.collect.ImmutableMap; |
| 5 | +import com.google.common.io.Resources; |
| 6 | +import graphql.GraphQL; |
| 7 | +import graphql.schema.DataFetcher; |
| 8 | +import graphql.schema.GraphQLSchema; |
| 9 | +import graphql.schema.idl.RuntimeWiring; |
| 10 | +import graphql.schema.idl.SchemaGenerator; |
| 11 | +import graphql.schema.idl.SchemaParser; |
| 12 | +import graphql.schema.idl.TypeDefinitionRegistry; |
| 13 | +import org.springframework.context.annotation.Bean; |
| 14 | +import org.springframework.stereotype.Component; |
| 15 | + |
| 16 | +import javax.annotation.PostConstruct; |
| 17 | +import java.io.IOException; |
| 18 | +import java.net.URL; |
| 19 | + |
| 20 | +@Component |
| 21 | +public class GraphQLProvider { |
| 22 | + |
| 23 | + GraphQL graphQL; |
| 24 | + |
| 25 | + DataFetcher<Object> fooDataFetcher = environment -> ImmutableMap.of("id", "fooId"); |
| 26 | + |
| 27 | + @PostConstruct |
| 28 | + public void init() throws IOException { |
| 29 | + URL url = Resources.getResource("schema.graphql"); |
| 30 | + String sdl = Resources.toString(url, Charsets.UTF_8); |
| 31 | + GraphQLSchema graphQLSchema = buildSchema(sdl); |
| 32 | + this.graphQL = GraphQL.newGraphQL(graphQLSchema).build(); |
| 33 | + } |
| 34 | + |
| 35 | + private GraphQLSchema buildSchema(String sdl) { |
| 36 | + TypeDefinitionRegistry typeRegistry = new SchemaParser().parse(sdl); |
| 37 | + RuntimeWiring runtimeWiring = buildWiring(); |
| 38 | + SchemaGenerator schemaGenerator = new SchemaGenerator(); |
| 39 | + GraphQLSchema graphQLSchema = schemaGenerator.makeExecutableSchema(typeRegistry, runtimeWiring); |
| 40 | + return graphQLSchema; |
| 41 | + } |
| 42 | + |
| 43 | + private RuntimeWiring buildWiring() { |
| 44 | + return RuntimeWiring.newRuntimeWiring() |
| 45 | + .type("Query", builder -> builder |
| 46 | + .dataFetcher("foo", fooDataFetcher)) |
| 47 | + .build(); |
| 48 | + } |
| 49 | + |
| 50 | + @Bean |
| 51 | + public GraphQL graphQL() { |
| 52 | + return graphQL; |
| 53 | + } |
| 54 | + |
| 55 | +} |
0 commit comments