Skip to content

Instantly share code, notes, and snippets.

@olim7t
Last active January 29, 2021 22:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save olim7t/5c2e0b9f338d742ee356135810d235f3 to your computer and use it in GitHub Desktop.
Save olim7t/5c2e0b9f338d742ee356135810d235f3 to your computer and use it in GitHub Desktop.
Multiple selections of the same field with different arguments, under different aliases
import graphql.GraphQL;
import graphql.Scalars;
import graphql.schema.DataFetcher;
import graphql.schema.DataFetchingEnvironment;
import graphql.schema.GraphQLSchema;
import static graphql.schema.FieldCoordinates.coordinates;
import static graphql.schema.GraphQLArgument.newArgument;
import static graphql.schema.GraphQLCodeRegistry.newCodeRegistry;
import static graphql.schema.GraphQLFieldDefinition.newFieldDefinition;
import static graphql.schema.GraphQLNonNull.nonNull;
import static graphql.schema.GraphQLObjectType.newObject;
import static graphql.schema.GraphQLSchema.newSchema;
public class AliasExample {
public static void main(String[] args) {
GraphQLSchema schema =
newSchema()
.query(
newObject()
.name("Query")
.field(
newFieldDefinition()
.name("user")
.type(
newObject()
.name("User")
.field(
newFieldDefinition()
.name("profilePic")
.argument(
newArgument()
.name("size")
.type(nonNull(Scalars.GraphQLInt))
.build())
.type(Scalars.GraphQLString)
.build())
.build())
.build())
.build())
.codeRegistry(
newCodeRegistry()
.dataFetcher(coordinates("Query", "user"), new UserFetcher())
.build())
.build();
GraphQL graphql = GraphQL.newGraphQL(schema).build();
executeAndPrint(graphql, "{ user { profilePic(size: 64) } }");
executeAndPrint(
graphql, "{ user { smallPic: profilePic(size: 64), bigPic: profilePic(size: 1024) } }");
}
private static class UserFetcher implements DataFetcher<UserDto> {
@Override
public UserDto get(DataFetchingEnvironment environment) {
return new UserDto();
}
}
public static class UserDto {
public String getProfilePic(DataFetchingEnvironment environment) {
int size = environment.getArgument("size");
return String.format("https://cdn.site.io/pic-4-%d.jpg", size);
}
}
private static void executeAndPrint(GraphQL graphql, String query) {
System.out.println(graphql.execute(query).getData().toString());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment