Allow creation of custom GraphQlSource instance

Closes gh-1086
This commit is contained in:
rstoyanchev
2025-03-26 16:01:22 +01:00
parent 4ce9ca71c2
commit 9180a7e4dc
2 changed files with 40 additions and 3 deletions

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2024 the original author or authors.
* Copyright 2002-2025 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -32,6 +32,7 @@ import graphql.schema.SchemaTransformer;
import graphql.schema.SchemaTraverser;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
/**
@@ -58,6 +59,8 @@ public abstract class AbstractGraphQlSourceBuilder<B extends GraphQlSource.Build
@Nullable
private Consumer<GraphQL.Builder> graphQlConfigurer;
private GraphQlSource.Factory graphQlSourceFactory = FixedGraphQlSource::new;
@Override
public B exceptionResolvers(List<DataFetcherExceptionResolver> resolvers) {
@@ -96,6 +99,13 @@ public abstract class AbstractGraphQlSourceBuilder<B extends GraphQlSource.Build
return self();
}
@Override
public B graphQlSourceFactory(GraphQlSource.Factory factory) {
Assert.notNull(factory, "GraphQlSource.Factory is required");
this.graphQlSourceFactory = factory;
return self();
}
@SuppressWarnings("unchecked")
private <T extends B> T self() {
return (T) this;
@@ -118,7 +128,7 @@ public abstract class AbstractGraphQlSourceBuilder<B extends GraphQlSource.Build
applyGraphQlConfigurers(builder);
return new FixedGraphQlSource(builder.build(), schema);
return this.graphQlSourceFactory.create(builder.build(), schema);
}
/**

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2023 the original author or authors.
* Copyright 2002-2025 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -149,6 +149,18 @@ public interface GraphQlSource {
*/
B configureGraphQl(Consumer<GraphQL.Builder> configurer);
/**
* Configure a factory to use to create the {@link GraphQlSource} instance
* to return from the {@link #build()} method.
* <p>By default, the instance is a simple container of {@link GraphQL} and
* {@link GraphQLSchema}. Applications can use this to create a different
* implementation that applies additional per-request logic.
* @param factory the factory to use
* @return the current builder
* @since 1.4.0
*/
B graphQlSourceFactory(Factory factory);
/**
* Build the {@link GraphQlSource} instance.
*/
@@ -240,4 +252,19 @@ public interface GraphQlSource {
}
/**
* Strategy to create the {@link GraphQlSource} instance in {@link Builder#build()}.
*/
interface Factory {
/**
* Create a {@link GraphQlSource} with the given inputs.
* @param graphQl the {@code GraphQLJava} initialized by the builder
* @param schema the schema initialized by the builder
* @return the created instance
*/
GraphQlSource create(GraphQL graphQl, GraphQLSchema schema);
}
}