Issue
I am trying to create a GraphQL endpoint on a Spring-Boot project and connect it to an Angular UI. I want to perform basic operations such as getting all elements, getting a specific element and updating an element. I am using Postman to see how my code is working.
Problem is that, currently my queries only work when I post them as a raw text value from Postman and don't work when I post them as graphql query since they are received differently by @RequestBody in my controller.
For Example:
I tried printing queries received by controller to see the problem and these are the outputs:
At first I did not mind the issue as it worked fine for raw text but then when tried to call endpoints from Angular, same thing happened with the graphql query of Postman.
These are the codes I wrote which may be helpful:
- schema.graphql:
query: Query
mutation: Mutation
}
type Query {
allOutages: [Outage]
outage(id: String): Outage
detail(id: String): Detail
}
type Mutation{
updateOutage(outageId:String, stage:String, crew_id:String, description:String, outage_cause:String): Outage
deleteOutage(id: String): String
}
type Outage {
outageId: String
startTimestamp: Float
endTimestamp: Float
stage: [String]
details: Detail
}
type Detail {
detailId: String
crew_id: String
description: String
outage_cause: String
}
- Controller:
@RestController
@RequestMapping
public class GraphQLController {
@Autowired
GraphQLService graphQLService;
@PostMapping(value="/outages")
public ResponseEntity<Object> getAllOutages(@RequestBody String query){
//System.out.println(query);
ExecutionResult execute = graphQLService.initiateGraphQL().execute(query);
return new ResponseEntity<>(execute, HttpStatus.OK);
//return null;
}
}
- Error Message I Get on Postman:
"errors": [
{
"message": "Invalid Syntax : offending token '\"query\"' at line 1 column 2",
"sourcePreview": "{\"query\":\"query {\\r\\n allOutages\\r\\n {\\r\\n outageId\\r\\n startTimestamp\\r\\n endTimestamp\\r\\n stage\\r\\n details\\r\\n {\\r\\n detailId\\r\\n crew_id\\r\\n description\\r\\n outage_cause\\r\\n }\\r\\n }\\r\\n}\"}\n",
"offendingToken": "\"query\"",
"locations": [
{
"line": 1,
"column": 2,
"sourceName": null
}
],
"errorType": "InvalidSyntax",
"path": null,
"extensions": null
}
]
- Warning Message I Get on IntelliJ:
Query did not parse : '{"query":"query {\r\n allOutages\r\n {\r\n outageId\r\n startTimestamp\r\n endTimestamp\r\n stage\r\n details\r\n {\r\n detailId\r\n crew_id\r\n description\r\n outage_cause\r\n }\r\n }\r\n}"}'
I will be really glad if anyone can help me with this issue.
Solution
I solved this issue by getting requestBody parameter as GraphQLRequestBody and converting it to ExecutionInput. I don't know why many tutorials use String as the type of query parameter.
Answered By - Punk
Answer Checked By - Cary Denson (JavaFixing Admin)