1 package net.sumaris.server.http.graphql;
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25 import com.fasterxml.jackson.databind.ObjectMapper;
26 import graphql.ExecutionInput;
27 import graphql.ExecutionResult;
28 import graphql.GraphQL;
29 import graphql.schema.GraphQLSchema;
30 import org.slf4j.Logger;
31 import org.slf4j.LoggerFactory;
32 import org.springframework.beans.factory.annotation.Autowired;
33 import org.springframework.http.MediaType;
34 import org.springframework.web.bind.annotation.PostMapping;
35 import org.springframework.web.bind.annotation.RequestBody;
36 import org.springframework.web.bind.annotation.ResponseBody;
37 import org.springframework.web.bind.annotation.RestController;
38
39 import javax.servlet.http.HttpServletRequest;
40 import java.util.Map;
41
42
43 @RestController
44 public class GraphQLRestController {
45
46 private static final Logger log = LoggerFactory.getLogger(GraphQLRestController.class);
47
48 private final GraphQL graphQL;
49
50 private final ObjectMapper objectMapper;
51
52 @Autowired
53 public GraphQLRestController(GraphQLSchema schema,
54 ObjectMapper objectMapper) {
55 this.graphQL = GraphQL.newGraphQL(schema).build();
56 this.objectMapper = objectMapper;
57 log.info(String.format("Starting GraphQL rest controller at {%s}...", GraphQLPaths.BASE_PATH));
58 }
59
60
61
62 @PostMapping(value = GraphQLPaths.BASE_PATH, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
63 @ResponseBody
64 public Map<String, Object> indexFromAnnotated(@RequestBody Map<String, Object> request, HttpServletRequest rawRequest) {
65 ExecutionResult executionResult = graphQL.execute(ExecutionInput.newExecutionInput()
66 .query((String) request.get("query"))
67 .operationName((String) request.get("operationName"))
68 .variables(GraphQLHelper.getVariables(request, objectMapper))
69 .context(rawRequest)
70 .build());
71
72 return GraphQLHelper.processExecutionResult(executionResult);
73 }
74
75
76
77 }