Apollo server - GraphQL - Syntax Error: Expected Name, found ) - graphql

I have seen there are many questions related to mine, but unfortunately, none of them work for me. That is why I am asking my question since I am still learning GraphQL.
I am working on a Project with NestJS, GraphQL, and Angular. I am using the Apollo client and the Apollo server to implement GraphQL.My approach is code first to schema creation. I am getting an error while doing an update mutation. I am using PostgreSQL as the database
Here is the mutation section of the generated schema
type Mutation {
updateVehicle(email: String!, vinNumber: String!, lastName: String!, firstName: String!, id: Int!): Vehicle!
deleteVehicle(id: Int!): Vehicle!
}
Here is the resolver for update mutation
#Mutation(returns => Vehicle)
async updateVehicle(
#Args({name: 'id', type: () => Int }) id: number,
#Args({name: 'firstName', type: () => String }) firstName: string,
#Args({name: 'lastName', type: () => String }) lastName: string,
#Args({name: 'vinNumber', type: () => String }) vinNumber: string,
#Args({name: 'email', type: () => String }) email: string) {
....
...
}
Here is the query that I tried on the playground of the apollo server.
mutation MyMutation(
$id: Int!,
$email:String!,
$firstName:String!,
$lastName:String!,
$vinNumber:String!){
updateVehicle(
id: $id,
email: $email,
firstName: $firstName,
lastName: $lastName,
vinNumber: $vinNumber){
id
email
firstName
lastName
vinNumber
}
}
In the query variables section, I put my values like below
{
"id": 2,
"firstName":"test",
"lastName": "test2",
"vinNumber": "1234",
"email": "test#live.com"
}
When I execute the query I am getting the below error message. Actually, I cannot figure out what it means.
{
"errors": [
{
"message": "Syntax Error: Expected Name, found \")\".: {\"response\":{\"errors\":[{\"message\":\"Syntax Error: Expected Name, found \\\")\\\".\",\"locations\":[{\"line\":3,\"column\":5}]}],\"status\":400},\"request\":{\"query\":\"{updateVehicleById(\\n input: {vehiclePatch: {id: 2}\\n ) {\\n vehicle {\\n ageOfVehicle \\n carMake \\n carModel \\n email\\n firstName \\n id\\n lastName\\n manufacturedDate\\n vinNumber\\n }\\n }}\"}}",
"locations": [
{
"line": 2,
"column": 3
}
],
"path": [
"updateVehicle"
],
"extensions": {
"code": "INTERNAL_SERVER_ERROR",
"exception": {
"response": {
"errors": [
{
"message": "Syntax Error: Expected Name, found \")\".",
"locations": [
{
"line": 3,
"column": 5
}
]
}
],
"status": 400
},
"request": {
"query": "{updateVehicleById(\n input: {vehiclePatch: {id: 2}\n ) {\n vehicle {\n ageOfVehicle \n carMake \n carModel \n email\n firstName \n id\n lastName\n manufacturedDate\n vinNumber\n }\n }}"
},
"stacktrace": [
"Error: Syntax Error: Expected Name, found \")\".: {\"response\":{\"errors\":[{\"message\":\"Syntax Error: Expected Name, found \\\")\\\".\",\"locations\":[{\"line\":3,\"column\":5}]}],\"status\":400},\"request\":{\"query\":\"{updateVehicleById(\\n input: {vehiclePatch: {id: 2}\\n ) {\\n vehicle {\\n ageOfVehicle \\n carMake \\n carModel \\n email\\n firstName \\n id\\n lastName\\n manufacturedDate\\n vinNumber\\n }\\n }}\"}}",
" at GraphQLClient.<anonymous> (E:\\Virtusa\\vehicle-managment-app\\vehicle-mgt-server3\\node_modules\\graphql-request\\dist\\index.js:170:35)",
" at step (E:\\Virtusa\\vehicle-managment-app\\vehicle-mgt-server3\\node_modules\\graphql-request\\dist\\index.js:63:23)",
" at Object.next (E:\\Virtusa\\vehicle-managment-app\\vehicle-mgt-server3\\node_modules\\graphql-request\\dist\\index.js:44:53)",
" at fulfilled (E:\\Virtusa\\vehicle-managment-app\\vehicle-mgt-server3\\node_modules\\graphql-request\\dist\\index.js:35:58)",
" at processTicksAndRejections (internal/process/task_queues.js:97:5)"
]
}
}
}
],
"data": null
}
I put the full error message for your reference. May I know the reason for this error? I tried changing the query and mutation as well. But it doesn't work. Appreciate your helpful response.

The code in this question is wrong, but the error makes it clear what the issue is:
"extensions": {
"code": "INTERNAL_SERVER_ERROR",
"exception": {
"response": {
"errors": [
{
"message": "Syntax Error: Expected Name, found \")\".",
"locations": [
{
"line": 3,
"column": 5
}
]
}
],
"status": 400
},
"request": {
"query": "{updateVehicleById(\n input: {vehiclePatch: {id: 2}\n ) {\n vehicle {\n ageOfVehicle \n carMake \n carModel \n email\n firstName \n id\n lastName\n manufacturedDate\n vinNumber\n }\n }}"
},
"stacktrace": [
"Error: Syntax Error: Expected Name, found \")\".: {\"response\":{\"errors\":[{\"message\":\"Syntax Error: Expected Name, found \\\")\\\".\",\"locations\":[{\"line\":3,\"column\":5}]}],\"status\":400},\"request\":{\"query\":\"{updateVehicleById(\\n input: {vehiclePatch: {id: 2}\\n ) {\\n vehicle {\\n ageOfVehicle \\n carMake \\n carModel \\n email\\n firstName \\n id\\n lastName\\n manufacturedDate\\n vinNumber\\n }\\n }}\"}}",
" at GraphQLClient.<anonymous> (E:\\Virtusa\\vehicle-managment-app\\vehicle-mgt-server3\\node_modules\\graphql-request\\dist\\index.js:170:35)",
" at step (E:\\Virtusa\\vehicle-managment-app\\vehicle-mgt-server3\\node_modules\\graphql-request\\dist\\index.js:63:23)",
" at Object.next (E:\\Virtusa\\vehicle-managment-app\\vehicle-mgt-server3\\node_modules\\graphql-request\\dist\\index.js:44:53)",
" at fulfilled (E:\\Virtusa\\vehicle-managment-app\\vehicle-mgt-server3\\node_modules\\graphql-request\\dist\\index.js:35:58)",
" at processTicksAndRejections (internal/process/task_queues.js:97:5)"
]
}
}
specifically has the request block that shows that the query throwing the error is
{updateVehicleById(
input: {vehiclePatch: {id: 2}
) {
vehicle {
ageOfVehicle
carMake
carModel
email
firstName
id
lastName
manufacturedDate
vinNumber
}
}}
The error says line 3 column 5 we can see the error is at ) { and looking closer, we can see the real error is on the previous line:
input: {vehiclePatch: {id: 2}
This input object has mismatched }, so it needs an extra } at the end of the line.

Related

Syntax error with graphQL "Expected Name..."

here is my code:
mutation CreateReviewForBook($ISBN: String!, $author: String!, $content: String!) {
createBookReview(ISBN: $ISBN, author: $author, content: $content) {
date
author
content
status
}
}
{
"ISBN": "0743273567",
"author": "Robert B.",
"content": "Great book!"
}
here is the question:
Using GraphQL, write a mutation named createBookReview that returns the fields: date, author, content, and status.
The arguments to the mutation should be the following:
ISBN = "0743273567"
author = "Robert B."
content = "Great book!"
Error:
{ "errors": [
{
"message": "Syntax Error: Expected Name, found String "ISBN"",
"extensions": {
"category": "graphql"
},
"locations": [
{
"line": 11,
"column": 3
}
]
} ] }
Can someone explain why am I getting this error?

Graphql Validation

My graphql schema looks like this:
type Query {
}
type Mutation {
addEmployee(
employeePayload: EmployeeRequest!
): EmployeeResponse
}
type EmployeeResponse {
transactionId: String!
status: String!
message: String!
}
type EmploymentHistory {
historyId: Int
}
type Address {
title: String
firstLine: String!
secondLine: String!
line3: String
county: String
country: String
postcode: String
}
type Employee {
employeeId: Int!
nationalityStatus: String!
issuingOfficeName: String!
surname: String
forenames: String
dateOfBirth: String
townOfBirth: String
countryOfBirth: String
gender: String
address: Address
}
type Details {
employmentHistory: [EmploymentHistory!]
employee: Employee!
}
type Meta {
messageId: String
action: String
}
input EmployeeRequest {
details: Details
meta: Meta
}
I have a json data , which looks like this:
{
"query": "mutation addEmployee($employeePayload:EmployeeRequest!){addEmployee(employeePayload: $employeePayload) { status transactionId message} }",
"variables": {
"employeePayload": {
"meta": {
"messageId": "4fc8ec8f-67ad-46d2-9fab-1234567",
"action": "Create"
},
"details": {
"employee": {
"employeeId": 123,
"nationalityStatus": "GBR",
"issuingOfficeName": "London",
"surname": "MARRIED",
"forenames": "LEON",
"address": {
"title": "MR",
"firstLine": "20 Maze street",
"secondLine": "Darlington",
"line3": "Darlington",
"county": "UNITED KINGDOM",
"country": "UNITED KINGDOM",
"postcode": "DW1H 9EX"
},
"dateOfBirth": "1980-05-18",
"townOfBirth": "SOME PLACE",
"countryOfBirth": "UNITED KINGDOM",
"gender": "M"
},
"employmentHistory": [
{
"historyId": 123
},
{
"historyId": 456
}
]
}
}
}
}
My code to validate the json against the schema is this:
try {
String query = "mutation addEmployee($employeePayload:EmployeeRequest!)
{addEmployee(employeePayload: $employeePayload) { status
transactionId message}}";
document = parser.parseDocument(query);
} catch (ParseCancellationException e) {
log.error("There seems to be an issue parsing the document" + e.getMessage());
}
Validator validator = new Validator();
List<ValidationError> validationErrors = validator.validateDocument(schema, document);
return validationErrors.isEmpty();
The query is not the full payload (that needs to be validated). The above validation always pass. Is there a way I can find the validation constraints like not null or wrong data type?

Apollo Federation schema, representations incomplete

I have this query:
getMyTransactions {
id
createdAt
}
And I got this error:
"message": "Cannot return null for non-nullable field Transaction.createdAt.",
"path": [
"_entities",
0,
"createdAt"
],
"extensions": {
"code": "INTERNAL_SERVER_ERROR",
"serviceName": "XXX",
"query": "query($representations:[_Any!]!){_entities(representations:$representations){...on Transaction{createdAt}}}",
"variables": {
"representations": [
{
"__typename": "Transaction",
"id": "29bf75e5-b79e-4a7d-a021-84a8b5662aa8"
},
{
"__typename": "Transaction",
"id": "616f3f8a-3c81-4d2e-bce0-03d031a15062"
}
]
},
//etc
Why isvariables.representations missing createdAt values? When I do a query directly to DynamoDB I can see createdAt values for all those 2 items.
My schemas are like this:
extend type Transaction #key(fields: "id") {
id: ID! #external
}
type Query {
getMyTransactions: [Transaction!]!
}
And the other schema has Transaction type:
type Transaction #key(fields: "id") {
id: ID!
createdAt: String!
}

Mutation arguments as object

I'm using the Go implemenatation of GraphQL.
How would you configure a mutation so that it can receive arguments with more than 1 level?
For exemple, here is the list of arguments I would like to pass to a mutation CreateUser:
mutation createUser($user: CreateUser!) {
createUser(input: $user)
}
{
"user": {
"name": {
"first": "John",
"last": "Doe"
},
"email": "john#doe.com"
}
}
(Notice that I dont want to use firstname and lastname but a name object instead)
And this is my (unsuccessful) attempt so far:
var CreateUserInput = graphql.FieldConfigArgument{
"input": &graphql.ArgumentConfig{
Description: "Input for creating a new user",
Type: graphql.NewNonNull(graphql.NewInputObject(graphql.InputObjectConfig{
Name: "CreateUser",
Fields: graphql.InputObjectConfigFieldMap{
"name": &graphql.InputObjectFieldConfig{
Type: graphql.NewNonNull(graphql.NewInputObject(graphql.InputObjectConfig{
Fields: graphql.InputObjectConfigFieldMap{
"first": &graphql.InputObjectFieldConfig{
Type: graphql.NewNonNull(graphql.String),
},
"last": &graphql.InputObjectFieldConfig{
Type: graphql.NewNonNull(graphql.String),
},
},
})),
},
"email": &graphql.InputObjectFieldConfig{
Type: graphql.NewNonNull(graphql.String),
},
},
})),
},
}
Apparently the subfields first and last are not recognized as this is what I get when I run this mutation:
{
"data": null,
"errors": [
{
"message": "Variable \"$user\" got invalid value {\"email\":\"john#doe.com\",\"name\":{\"first\":\"john\",\"last\":\"doe\"}}.\nIn field \"name\": In field \"first\": Unknown field.\nIn field \"name\": In field \"last\": Unknown field.",
"locations": [
{
"line": 1,
"column": 21
}
]
}
]
}
Is this even possible?
EDIT: See comments in the accepted answer for the solution.
This are my first ever lines of Go but I will try to convey what I think the problem is.
First lets talk about the structure you want to be going for. I will use SDL here:
type Mutation {
createUser(user: CreateUser!): Boolean! # Maybe return user type here?
}
input CreateUser {
name: CreateUserName!
email: String!
}
input CreateUserName {
first: String!
last: String!
}
Okay now that we know that we need two input types lets get started!
var CreateUserName = graphql.NewInputObject(graphql.InputObjectConfig{
Name: "CreateUserName",
Fields: graphql.InputObjectConfigFieldMap{
"first": &graphql.InputObjectFieldConfig{
Type: graphql.NewNonNull(graphql.String),
},
"last": &graphql.InputObjectFieldConfig{
Type: graphql.NewNonNull(graphql.String),
},
},
})
var CreateUser = graphql.NewInputObject(graphql.InputObjectConfig{
Name: "CreateUser",
Fields: graphql.InputObjectConfigFieldMap{
"name": &graphql.InputObjectFieldConfig{
Type: graphql.NewNonNull(CreateUserName),
},
"email": &graphql.InputObjectFieldConfig{
Type: graphql.NewNonNull(graphql.String),
},
},
})
Now all that should be left is adding the mutation field to your mutation object type.

sailsjs: model email validation seems not to work

On a fresh sailsjs installation, I've got a test model defined like this:
module.exports = {
attributes: {
username:{
type:'string'
}
,email:{
type:'string'
,email:true
}
}
};
And if I navigate to this:
http://localhost:1337/user/create?username=stratboy1&email=test#wow.com
I get this error:
{
"error": "E_VALIDATION",
"status": 400,
"summary": "1 attribute is invalid",
"model": "User",
"invalidAttributes": {
"email": [
{
"rule": "email",
"message": "\"email\" validation rule failed for input: 'test#wow.com'"
}
]
}
}
Any of you knows why?
I've come across this earlier but don't quite remember the cause.
As a quick fix, you can substitute
email: { type: 'string', email: true }
with
email: { type: 'email' }

Resources