Last active
January 29, 2021 22:14
-
-
Save olim7t/5c2e0b9f338d742ee356135810d235f3 to your computer and use it in GitHub Desktop.
Multiple selections of the same field with different arguments, under different aliases
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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