【发布时间】:2018-12-19 01:11:57
【问题描述】:
这是我的突变代码,其中我使用具有名称、电子邮件、密码的用户类型,并且我为注册用户和登录用户进行了两次突变。我已经搜索了有关 graphql 的所有文档并阅读了所有与身份验证相关的博客,但无法得到从突变中返回令牌的答案
const mutation = new GraphQLObjectType({
name: "Mutation",
fields: {
addUser: {
type: UserType,
args: {
name: { type: GraphQLString },
email: { type: GraphQLString },
password: { type: GraphQLString },
avatar: { type: GraphQLString }
},
resolve(parentValue, args) {
const avatar = gravatar.url(args.email);
return bcrypt
.hash(args.password, 10)
.then(hash => {
args.password = hash;
const newUser = new User({
name: args.name,
email: args.email,
password: args.password,
avatar
});
return newUser
.save()
.then(user => user)
.catch(e => e);
})
.catch(e => e);
}
},
login: {
name: "Login",
type: UserType,
args: {
email: { type: GraphQLString },
password: { type: GraphQLString }
},
resolve(parentValue, args, context) {
return User.findOne({ email: args.email })
.then(user => {
if (user) {
return bcrypt
.compare(args.password, user.password)
.then(isValid => {
if (!isValid) {
throw new Error({ message: "password Incrrect" });
} else {
const token = jwt.sign(
{ name: user.name, id: user.id },
"mySecret"
);
return user;
}
})
.catch(e => e);
} else {
throw new Error({ message: "email Incorrect" });
}
})
.catch(e => e);
}
}
}
});
这是我的用户类型
const UserType = new GraphQLObjectType({
name: "User",
fields: {
id: { type: GraphQLString },
name: { type: GraphQLString },
email: { type: GraphQLString },
password: { type: GraphQLString },
avatar: { type: GraphQLString }
}
});
【问题讨论】: