简体   繁体   English

Graphql突变导致不返回数据

[英]Graphql mutation sequelize not returning data

am trying to do login with graphql, i want to first of all check if the email exist in the database, then if the email exist, then i will compare the password with the bcrypt hash in the password, if it returns true, then i will update the token in the users table in the database, but when i tested it with this 我试图用graphql登录,我想首先检查数据库中是否存在电子邮件,然后如果电子邮件存在,那么我将密码与密码中的bcrypt哈希进行比较,如果返回true,则我将更新数据库中用户表中的令牌,但是当我对此进行测试时

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

it returned this instead of te token in the database 它在数据库中返回了该令牌而不是te令牌

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

here is my code 这是我的代码

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")
                }
            })
        });
    }
};

pls ow can i make it return the token 请问我可以让它返回令牌吗

Try using findByIdAndUpdate with {new: true} for updated document. 尝试将findByIdAndUpdate{new: true}用于更新的文档。 So your code will be something like this 所以你的代码将是这样的

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")
            }
        })
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM