【问题标题】:Graphql mutation sequelize not returning dataGraphql突变续集不返回数据
【发布时间】:2019-06-20 19:41:06
【问题描述】:

我正在尝试使用graphql登录,我想首先检查数据库中是否存在电子邮件,然后如果电子邮件存在,那么我会将密码与密码中的bcrypt哈希进行比较,如果它返回true ,然后我将更新数据库中用户表中的令牌,但是当我用这个测试它时

mutation {
  loginUser(user: {email: "kmd@vh.id", password: "1345968"}) {
    password
  }
}

它返回 this 而不是数据库中的 te 令牌

mutation {
  loginUser(user: {email: "kmd@vh.id", password: "1345968"}) {
    token
  }
}

这是我的代码

import models from '../../../models/index.js';
import User from '../../types/user.js';
import UserInput from '../../inputs/user.js';
const jwt = require('jsonwebtoken')
const bcrypt = require('bcryptjs')
require('dotenv').config()
const fs = require('fs');
const path = require('path');

var privateKey = fs.readFileSync(path.join(__dirname, '../../key/private.key'), 'utf8');
export default {
    type: User,
    args: {
        user: {
            type: UserInput
        }
    },
    resolve (_,args) {
        return models.user.findOne({
            where: {email: args.user.email}  
        }).then((fUser)=> {
            bcrypt.compare(args.user.password, fUser.password, function (err, res) {
                if (res) {
                    return models.user.findById(fUser.id).then((user) => {
                        return user.update({ token: jwt.sign({id:fUser.id, role:fUser.role, email:fUser.email}, privateKey, { expiresIn: '1h' }) });
                    });
                } else {
                  console.log(err+" error")
                }
            })
        });
    }
};

请问我可以让它返回令牌

【问题讨论】:

    标签: node.js sequelize.js graphql


    【解决方案1】:

    尝试使用findByIdAndUpdate{new: true} 来更新文档。所以你的代码会是这样的

    return models.user.findOne({
            where: {email: args.user.email}  
        }).then((fUser)=> {
            bcrypt.compare(args.user.password, fUser.password, function (err, res) {
                if (res) {
                    return models.user.findByIdAndUpdate(fUser.id, {
                      $set: {
                        token: jwt.sign(
                          { id:fUser.id, role:fUser.role, email:fUser.email },
                          privateKey,
                          { expiresIn: '1h' }
                       )}}, { new: true })
    
                } else {
                  console.log(err+" error")
                }
            })
        });
    

    【讨论】:

      猜你喜欢
      • 2018-06-06
      • 2020-02-25
      • 1970-01-01
      • 2017-11-27
      • 2021-04-01
      • 2018-10-17
      • 2021-02-27
      • 2018-12-19
      • 2019-06-28
      相关资源
      最近更新 更多