0
votes

I'm having a little trouble when querying inside a mutation, I believe maybe I'm not calling correctly the query, because it executes but is not waiting for the response so I get an undefined value, please correct me.

Please note that I'm using prisma-binding

This is my mutation resolvers:

const Mutation = {

  async signUp(parent, args, ctx, info) {
    const password = await bcrypt.hash(args.password, 10)
    const user = await ctx.db.mutation.createUser({ data: {...args, password} })
    const token = jwt.sign({ userId: user.id }, process.env.PRISMA_SECRET)

    return {
      token,
      user,
    }
  },

  async login(parent, args, ctx, info) {
    const user = await ctx.db.query.users( {where:{email: args.email}}, info)

    if (!user) {
      throw new Error('No such user found')
    }

    const valid = bcrypt.compare(args.password, user.password)
    if (!valid) {
      throw new Error('Invalid password')
    }

    const token = jwt.sign({ userId: user.id }, process.env.PRISMA_SECRET)

    return {
      token,
      user,
    }
  },


};

module.exports = Mutation;

In the login function when querying the user or users I try both queries even knowing I have email as unique field it always print No such user found due I receive undefined, IDK if it's because prisma-binding or not doing correctly the function call to prisma.

Here is my schema.graphql

type Query {
  // some queries 
}

type Mutation {
  signUp(
    name: String!
    email: String!
    password: String!
  ): AuthPayLoad

  login(
    email: String!
    password: String!
  ): AuthPayLoad

}

type AuthPayLoad {
  token: String
  user: User
}

So for prisma-binding I don't have to define the query users(), the binding will handle that right?? Even if was that, I would have another error which isn't the case.

Maybe I'm missing some little detail, will be grateful if someone point me to the right direction.

Thanks in advance...

1
Is email part of 'data' in the user query? If so you'd need const user = await ctx.db.query.user( {where:{email: args.data.email}}) - Andrew1325

1 Answers

0
votes

You are passing the wrong selection set to the query. You are returning AuthPayload in login mutation but you are passing it to the user query which is surely incompatible.

try this

  async login(parent, args, ctx, info) {
    const user = await ctx.db.query.user( {where:{email: args.email}},`{ id name email }`) // pass in the other fields you want in this selection set

    if (!user) {
      throw new Error('No such user found')
    }

    const valid = bcrypt.compare(args.password, user.password)
    if (!valid) {
      throw new Error('Invalid password')
    }

    const token = jwt.sign({ userId: user.id }, process.env.PRISMA_SECRET)

    return {
      token,
      user,
    }
  },