首页 > 解决方案 > Graphql 的登录突变未找到用户

问题描述

我正在尝试使用 graphql 和 mongodb 创建身份验证服务。我已经创建了我的登录突变,它接受了电子邮件和密码。我正在使用 bcrypt 来散列和取消散列密码。

这不是导入问题或 mongodb 问题,而是 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;
                  },
                },
              }});

它应该返回一个 jwt 令牌,以后可以用于身份验证。首先,我在浏览器的 graphiql 中运行它:

mutation{
  login(email: "ammarthayani@gmail.com", password:"password"){
  }
}

它在控制台中给了我这个:“语法错误:预期名称,找到

然后我尝试了:

mutation{
  login(email: "ammarthayani@gmail.com", password:"password"){
    username
  }
}

这给了我:字段 \"login\" 不能有选择,因为类型 \"String\" 没有子字段。

标签: mongodbmongoosejwtschemagraphql

解决方案


类型上login字段的Mutation类型是GraphQLString,它是一个标量。由于标量是叶节点,它们没有选择集(即其他“子”字段)。从规格

如果 selectionType 是标量或枚举:

  • 该选择的子选择集必须为空

如果 selectionType 是接口、联合或对象

  • 该选择的子选择集不得为空

花括号用于指示选择集,因此当字段的返回类型是标量或枚举时,不应使用它们。您的查询需要简单的是:

mutation {
  login(email: "ammarthayani@gmail.com", password:"password")
}

推荐阅读