|
| 1 | +package com.baeldung.graphql.handler; |
| 2 | + |
| 3 | +import graphql.ExecutionResult; |
| 4 | +import graphql.GraphQL; |
| 5 | +import graphql.schema.DataFetchingEnvironment; |
| 6 | +import ratpack.handling.Context; |
| 7 | +import ratpack.handling.Handler; |
| 8 | + |
| 9 | +import java.util.ArrayList; |
| 10 | +import java.util.LinkedHashMap; |
| 11 | +import java.util.List; |
| 12 | +import java.util.Map; |
| 13 | +import java.util.logging.Logger; |
| 14 | + |
| 15 | +import com.baeldung.graphql.entity.User; |
| 16 | +import com.baeldung.graphql.schema.UserSchema; |
| 17 | +import com.baeldung.graphql.utils.SchemaUtils; |
| 18 | + |
| 19 | +import static ratpack.jackson.Jackson.json; |
| 20 | + |
| 21 | +public class UserHandler implements Handler { |
| 22 | + private static final Logger LOGGER = Logger.getLogger(UserHandler.class.getSimpleName()); |
| 23 | + private GraphQL graphql; |
| 24 | + private static List<User> users = new ArrayList<>(); |
| 25 | + |
| 26 | + public UserHandler() throws Exception { |
| 27 | + graphql = new GraphQL(new UserSchema().getSchema()); |
| 28 | + } |
| 29 | + |
| 30 | + @Override |
| 31 | + public void handle(Context context) throws Exception { |
| 32 | + context.parse(Map.class) |
| 33 | + .then(payload -> { |
| 34 | + Map<String, Object> parameters = (Map<String, Object>) payload.get("parameters"); |
| 35 | + ExecutionResult executionResult = graphql.execute(payload.get(SchemaUtils.QUERY) |
| 36 | + .toString(), null, this, parameters); |
| 37 | + Map<String, Object> result = new LinkedHashMap<>(); |
| 38 | + if (executionResult.getErrors() |
| 39 | + .isEmpty()) { |
| 40 | + result.put(SchemaUtils.DATA, executionResult.getData()); |
| 41 | + } else { |
| 42 | + result.put(SchemaUtils.ERRORS, executionResult.getErrors()); |
| 43 | + LOGGER.warning("Errors: " + executionResult.getErrors()); |
| 44 | + } |
| 45 | + context.render(json(result)); |
| 46 | + }); |
| 47 | + } |
| 48 | + |
| 49 | + public static List<User> getUsers() { |
| 50 | + return users; |
| 51 | + } |
| 52 | + |
| 53 | + public static List<User> getUsers(DataFetchingEnvironment env) { |
| 54 | + return ((UserHandler) env.getSource()).getUsers(); |
| 55 | + } |
| 56 | +} |
0 commit comments