Apollo GraphQL“不能为不可为空的字段 Mutation.createUser 返回 null" [英] Apollo GraphQL "Cannot return null for non-nullable field Mutation.createUser"

查看:18
本文介绍了Apollo GraphQL“不能为不可为空的字段 Mutation.createUser 返回 null"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这是一个比较常见的问题,但我的实现与其他帖子不同.我正在使用我无法工作的最基本的实现.我使用 Sequelize 和 MySQL 作为数据库实现.

I know this is a somewhat common issue, but my implementation differs from the other posts. I'm using the most basic implementation which I can't get to work. I'm using Sequelize with MySQL as the database implementation.

解析器.js

const resolvers = {
    Query: {
        async getStudent (root, { id }, { models }) {
            return models.User.findByPk(id)
        },
    },
    Mutation: {
        async createUser (root, { name, email }, { models }) {
            return models.User.create({
                name,
                email
            })
        },
    },
}

schema.js

const { gql } = require('apollo-server-express');
const typeDefs = gql`
    type User {
        id: Int!
        name: String!
        email: String!
    }
    type Query {
        getUser(id: Int!): User
        getAllUsers: [User!]!
    }
    type Mutation {
        createUser(name: String!, email: String!): User!
    }`
module.exports = typeDefs;

用户模型

'use strict';
module.exports = (sequelize, DataTypes) => {
  const User = sequelize.define('User', {
    name: DataTypes.STRING,
    email: DataTypes.STRING
  }, {});
  User.associate = function(models) {
    // associations can be defined here
  };
  return User;
};

当运行以下突变时:

mutation{ createUser(name:"Nate", email:"nate@test.com"){编号 } }

mutation{ createUser(name:"Nate", email:"nate@test.com"){ id } }

我收到:

错误":[{"message": "不能为不可为空的字段 Mutation.createUser 返回 null.",地点":[{线":2,列":3}],小路": [创建用户"],

"errors": [ { "message": "Cannot return null for non-nullable field Mutation.createUser.", "locations": [ { "line": 2, "column": 3 } ], "path": [ "createUser" ],

推荐答案

就我而言,这是因为 createUser 调用不是异步的.希望这可以帮助某人:

In my case it was because the createUser call was not asynchronous. Hopefully this helps someone:

return models.User.create({
    name,
    email
})

这篇关于Apollo GraphQL“不能为不可为空的字段 Mutation.createUser 返回 null"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆