0
votes

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: "[email protected]", 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:

schema hings

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?

1
I believe that you if you don't specify the graphql operation when making the request, it defaults to query (which would explain the error message). I am not sure the exact syntax, but maybe you could try something mutation { signup(email: "[email protected]", password: "321321", role: "admin") }Matt
As an aside, you probably shouldn't use buildSchema.Daniel Rearden
Ok, I'll look into that as soon as I get this working. Or could it be that buildSchema is messing things around?AFMeirelles

1 Answers

4
votes

You need to specify the operation type (query, mutation or subscription) like this:

mutation {
  signup(email: "[email protected]", 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.