Started messing around with GraphQL, but I'm stuck with this error. Not sure if it's a problem in the schema definition or in the query.
const express_graphql = require('express-graphql')
const { buildSchema } = require('graphql')
const users = require('../users/translator')
const schema = buildSchema(`
type User {
id: ID
email: String
role: String
}
type Query {
user(id: ID!): User
users: [User]
token(email: String!, password: String!): String!
}
type Mutation {
signup(email: String!, password: String!, role: String!): ID
}`
)
const resolvers = {
users: users.getAll,
user: users.getById,
token: users.login,
signup: users.create,
}
module.exports = app => {
// GraphQL route
app.use('/graphql', express_graphql({
schema,
rootValue: resolvers,
graphiql: true,
}))
}
app
is an express.js server while const users
holds the logic. I'm able to fetch users and tokens, but when I try to POST a mutation
{
signup(email: "my@email.com", password: "321321", role: "admin")
}
I get the error Cannot query field "signup" on type "Query"
. By looking at the GraphiQL suggestions after reading the schema from the server, it looks like the signup mutation doesn't even get exported:
Some tutorials say I should export resolvers using
const resolvers = {
query: {
users: users.getAll,
user: users.getById,
token: users.login,
},
mutation: {
signup: users.create,
}
}
But it doesn't work either. Any hints?
You need to specify the operation type (query
, mutation
or subscription
) like this:
mutation {
signup(email: "my@email.com", password: "321321", role: "admin")
}
If the operation type is omitted, the operation is assumed to be a query. This is called "query shorthand notation", but only works if your operation is unnamed and does not include any variable definitions.
It's good practice to always include the operation type regardless.