我正在尝试使用graphql和mongodb创建身份验证服务。我创建了我的登录名突变,其中包含了电子邮件和密码。我正在使用bcrypt来对密码进行哈希处理和取消哈希处理。
这不是graphql的导入问题或mongodb问题。
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 \”没有子字段。
答案 0 :(得分:1)
您的login
类型的Mutation
字段的类型为GraphQLString
,它是一个标量。由于标量是叶节点,因此它们没有选择集(即其他“子”字段)。 From the spec:
如果selectionType是标量或枚举:
- 该选择的子选择集必须为空
如果selectionType是接口,联合或对象
- 该选择的子选择集不能为空
曲线括号用于指示选择集,因此,当字段的返回类型为标量或枚举时,不应使用它们。您的查询必须简单地是:
mutation {
login(email: "ammarthayani@gmail.com", password:"password")
}