MCPcopy Index your code
hub / github.com/graphql-java/graphql-java / DirectivesExamples

Class DirectivesExamples

src/test/groovy/readme/DirectivesExamples.java:29–199  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

27import java.util.Map;
28
29@SuppressWarnings({"Convert2Lambda", "unused", "ClassCanBeStatic"})
30public class DirectivesExamples {
31
32 static class AuthorisationCtx {
33 boolean hasRole(String roleName) {
34 return true;
35 }
36
37 static AuthorisationCtx obtain() {
38 return null;
39 }
40 }
41
42 class AuthorisationDirective implements SchemaDirectiveWiring {
43
44 @Override
45 public GraphQLFieldDefinition onField(SchemaDirectiveWiringEnvironment<GraphQLFieldDefinition> environment) {
46 String targetAuthRole = (String) environment.getAppliedDirective().getArgument("role").getArgumentValue().getValue();
47
48 //
49 // build a data fetcher that first checks authorisation roles before then calling the original data fetcher
50 //
51 DataFetcher originalDataFetcher = environment.getFieldDataFetcher();
52 DataFetcher authDataFetcher = new DataFetcher() {
53 @Override
54 public Object get(DataFetchingEnvironment dataFetchingEnvironment) throws Exception {
55 AuthorisationCtx authContext = dataFetchingEnvironment.getGraphQlContext().get("authContext");
56
57 if (authContext.hasRole(targetAuthRole)) {
58 return originalDataFetcher.get(dataFetchingEnvironment);
59 } else {
60 return null;
61 }
62 }
63 };
64 //
65 // now change the field definition to have the new authorising data fetcher
66 return environment.setFieldDataFetcher(authDataFetcher);
67 }
68 }
69
70 void authWiring() {
71
72 //
73 // we wire this into the runtime by directive name
74 //
75 RuntimeWiring.newRuntimeWiring()
76 .directive("auth", new AuthorisationDirective())
77 .build();
78
79 }
80
81 String query = "";
82
83 void contextWiring() {
84
85 AuthorisationCtx authCtx = AuthorisationCtx.obtain();
86

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…