How to load GraphQL query file and call GraphQL API in Spring Boot

518 views Asked by At

I have a spring boot microservice which uses Netflix DGS GraphQL framework which calls multiple backends/micro services. Most of the backend services are graphQL. For my orchestration I need to load all the service GraphQL queries and use them.

Is there any elegant way to load the GraphQL queries or .graphql files? Currently loading the files as below.

InputStream inputStream = (new ClassPathResource(path)).getInputStream();
var3 = StreamUtils.copyToString(inputStream, StandardCharsets.UTF_8);

Doing this kind of code in @PostConstruct block of code. Instead of this does spring framework itself can able to resolve the files if we give the path or if we give path can framework load the query in a variable dynamically like bleow.

Expecting below line should load this query string without any custom code. Or can we load all the queries in a config file during startup and use it where ever we need.

@Autowired("$graphql/queries/fileQuery.graphql")
private String fileQuery
1

There are 1 answers

3
Brian Clozel On BEST ANSWER

As a general rule, beans should only be created for application components with well-defined types. Resolving query files contents and injecting those as String in your application looks like an anti-pattern to me.

Here you should instead use the built-in feature for this: drop all your .graphql query files in src/main/resources/graphql-documents and let the GraphQL client load them for you by their name::

// assuming a 'src/main/resources/graphql-documents/projectReleases.graphql' file
Mono<Project> projectMono = graphQlClient.documentName("projectReleases") 
        .variable("slug", "spring-framework") 
        .retrieve()
        .toEntity(Project.class);

Check out the Spring for GraphQL client reference documentation for more.