如何修复Apollo-GraphQL为突变中的可为空字段返回null的问题?

时间:2019-07-18 10:47:15

标签: postgresql graphql babel knex.js apollo-server

我正在制作一个演示GraphQL API作为学习项目,它使用Apollo-server-express,Babel,Knex.js和PostgreSQL。

查询解析器运行良好,但在突变时发现了一个问题,非空字段返回null。

// userMutation.js

import knex from '../libs/knex';

const userMutation = {
  create: function(data) {
    return knex('users')
      .insert(data)
      .returning('*');
  }
};

...

// Mutation.js

import userQuery from '../../queries/userQuery';
import userMutation from '../../mutations/userMutation';

const Mutation = {
  async createUser(parent, args, ctx, info) {
    const { data } = args;

    const emailTaken = userQuery.getByEmail(data.email);
    if (emailTaken) throw new Error('Email is taken');

    const user = {
      ...data
    };

    const result = await userMutation.create(user);

    console.log(result);
    return result;
  }
};

// typeDefs.js

type Mutation {
  createUser(data: CreateUserInput!): User
}

我做了一个突变:

mutation {
  createUser(
    data: { lastName: "One", email: "some@one.com", password: "okay123" }
  ) {
    email
  }
}

然后...

{
  "errors": [
    {
      "message": "Cannot return null for non-nullable field User.email.",
      "locations": [
        {
          "line": 3,
          "column": 5
        }
      ],
      "path": [
        "createUser",
        "email"
      ],
      "extensions": {
        "code": "INTERNAL_SERVER_ERROR"
      }
    }
  ],
  "data": {
    "createUser": null
  }
}

我在做什么错?请帮忙。

0 个答案:

没有答案