我开始使用带有apollo-server-express
and的 graphql 开发一个 express API graphql-tools
。我的注册用户流程步骤是:
用户提交用户名、电子邮件和密码。
服务器通过 Mailgun 向用户发送一封电子邮件,其中包含由 . 生成的唯一链接
uuid
。用户点击链接以验证注册。
但我正在努力解决如何在解析器中绑定突变。见片段:
服务器.js
const buildOptions = async (req, res, done) => {
const user = await authenticate(req, mongo.Users)
return {
schema,
context: {
dataloaders: buildDataloaders(mongo),
mongo,
user
},
}
done()
}
// JWT setting
app.use('/graphAPI',
jwt({
secret: JWT_SECRET,
credentialsRequired: false,
}),
graphqlExpress(buildOptions),
res => data => res.send(JSON.stringify(data))
)
解析器上的突变
signupUser: async (root, data, {mongo: { Users }}) => {
// Check existed accounts,
// if account is not exist, assign new account
const existed = await Users.findOne({email: data.email})
if (!existed) {
// create a token for sending email
const registrationToken = {
token: uuid.v4(),
created_at: new Date(),
expireAfterSeconds: 3600000 * 6 // half day
}
const newUser = {
name: data.name,
email: data.email,
password: await bcrypt.hash(data.password, 10),
created_at: new Date(),
verification_token: registrationToken,
is_verified: false,
}
const response = await Users.insert(newUser)
// send and email to user
await verifyEmail(newUser)
return Object.assign({id: response.insertedIds[0]}, newUser)
}
// Throw error when account existed
const error = new Error('Email existed')
error.status = 409
throw error
},
// VERIFY USER
// Set verify to true (after user click on the link)
// Add user to mailist
verifiedUser: async (root, data, {mongo: { Users }}) => {
await Users.updateOne(
{ email: data.email },
{
set: {is_verified: true},
unset: {verification_token: {token: ''}}
}
)
},
路由配置
routes.get('/verify?:token', (req, res, next) => {
res.render('verified', {title: 'Success'})
})
路由配置是我卡住的地方,因为对象通过内部的上下文传递给所有解析器graphqlExpress
任何人都可以帮助我或为我推荐任何相关的文章。非常感谢。