0
votes

I am trying to create an authentication service with graphql and mongodb. I have created my login mutation which takes in the email and password. I am using bcrypt to hash and unhash the passwords.

It's not a import issue or a mongodb issue it's graphql.

const UserType = new GraphQLObjectType({
    name: 'User',
    fields: () => ({
        id: {type: GraphQLID},
        username: {type: GraphQLString},
        email: {type: GraphQLString},
        password: {type: GraphQLString},
        institution: {
            type: InstitutionType,
            resolve(parent, args){
                return Institution.findById(parent.institutionId)
            }
        }
    })
});
login:{
                type:GraphQLString,
                args:{
                    email: {type: GraphQLString},
                    password: {type: GraphQLString}
                },
                resolve: async (parent, { email, password }, { models, SECRET }) => {
                    const user = await models.User.findOne({ where: { email } });
                    if (!user) {
                      throw new Error('No user with that email');
                    }

                    const valid = await bcrypt.compare(password, user.password);
                    if (!valid) {
                      throw new Error('Incorrect password');
                    }

                    const token = jwt.sign(
                      {
                        user: _.pick(user, ['id', 'username']),
                      },
                      SECRET,
                      {
                        expiresIn: '1y',
                      },
                    );

                    return token;
                  },
                },
              }});

It should return a jwt token which can later be used for authentication. First I was running this in the graphiql in my browser:

mutation{
  login(email: "[email protected]", password:"password"){
  }
}

and it was giving me this in the console : "Syntax Error: Expected Name, found

Then I tried:

mutation{
  login(email: "[email protected]", password:"password"){
    username
  }
}

which gave me: Field \"login\" must not have a selection since type \"String\" has no subfields.

1

1 Answers

1
votes

The type for the login field on your Mutation type is GraphQLString, which is a scalar. Since scalars are leaf nodes, they do not have a selection set (i.e. other "child" fields). From the spec:

If selectionType is a scalar or enum:

  • The subselection set of that selection must be empty

If selectionType is an interface, union, or object

  • The subselection set of that selection must NOT BE empty

Curly brackets are used to indicate a selection set, so they should not be used when the return type for a field is a scalar or an enum. Your query needs to simple be:

mutation {
  login(email: "[email protected]", password:"password")
}