我在将数据返回到 GraphQL 突变时遇到了一些问题。在突变中,您提供电子邮件和密码进行注册。从那里,GraphQL 应该返回一个包含 usersId 的 JSON 网络 token 。
即使密码被散列并且电子邮件和密码被保存到数据库并且 JWT 是用用户 id 作为有效载荷制作的,它还是用这个响应
{
"data": {
"signUp": {
"token": null,
"email": null
}
}
}
这是 GraphQL 查询:
mutation {
signUp(email: "johndoe@example.com", password: "password") {
token //Should return a JWT
email // Should return the users email address
}
}
这是突变:(运行突变时,它会将 JWT 记录到控制台但不会将其返回给 GraphQL)
const mutation = new GraphQLObjectType({
name: 'Mutation',
fields: {
signUp: {
type: UserType,
args: {
email: { type: new GraphQLNonNull(GraphQLString) },
password: { type: new GraphQLNonNull(GraphQLString) }
},
resolve (parentValue, args) {
return signUp(args) // Calls a function in another file with the args
.then((result) => {
console.log(result) // Logs the JWT to the console.
return result
})
}
}
}
})
这是用户类型:
const UserType = new GraphQLObjectType({
name: 'UserType',
fields: {
id: { type: GraphQLID },
email: { type: GraphQLString },
token: { type: GraphQLString }
}
})
这里是我们的注册函数:
function signUp ({ email, password }) {
return new Promise((resolve, reject) => {
bcrypt.hash(password, 10, function(err, password) {
const userKey = datastore.key('User')
const entity = {
key: userKey,
data: {
email,
password
}
}
datastore.insert(entity)
.then(() => {
let userId = userKey.path[1]
jwt.sign({userId}, 'secret', function (err, token) {
resolve(token)
})
})
})
})
}
最佳答案
正在关注 your comment :
由于您的 signUp
突变是 UserType
,因此您不应使用对象 { token: ... }
来解析它,而应使用用户
对象。这将允许您在执行突变时查询用户的其他字段。
按照你的例子,这可能是:
function signUp ({ email, password }) {
return new Promise((resolve, reject) => {
bcrypt.hash(password, 10, function(err, password) {
if (err) return reject(err);
const userKey = datastore.key('User')
const userId = userKey.path[1];
jwt.sign({userId}, 'secret', function (err, token) {
if (err) return reject(err);
const entity = {
key: userKey,
data: {
email,
password,
token,
},
};
datastore.insert(entity)
.then(inserted => resolve(inserted));
});
});
});
}
关于javascript - 从 Promise 返回数据到 GraphQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44537696/