GraphQL 查询给出错误,但它仍然更新我的数据库

问题描述 投票:0回答:1

我正在 React 中制作一个项目,使用 apollo-server-express、graphQL 和 postgreSQL,我已经完成了类型定义以及一些查询和突变,但具体有 3 个无法正常工作。

他们三个给出了相同的错误,所以我只显示一个突变。 在我的 postgreSQL 中,我创建了这个表:

CREATE TABLE IF NOT EXISTS tb_evaluator(
    id SERIAL NOT NULL,
    name VARCHAR(255) NOT NULL,
    profession VARCHAR(255) NOT NULL,
    performance_exp VARCHAR(20) NOT NULL,
    app_exp VARCHAR(20) NOT NULL,
    ag_exp VARCHAR(20) NOT NULL,
    evaluation_date VARCHAR(255) NOT NULL,
    PRIMARY KEY (id)
);

然后在我的项目中,我创建了一个包含类型定义、查询和突变的 js 文件。

const { gql } = require('apollo-server-express')

const typedefs = gql`
type Evaluator {
  id: ID!
  name: String!
  profession: String!
  performanceExp: String!
  appExp: String!
  agExp: String!
  evaluationDate: String!
}

type Mutation {
  addEvaluator(input: AddEvaluatorInput!): Evaluator!
}

input AddEvaluatorInput {
  name: String!
  profession: String!
  performanceExp: String!
  appExp: String!
  agExp: String!
  evaluationDate: String!
}
`;

module.exports = typedefs;

在其他文件中我创建了解析器,对于本例,解析器是:

const { Pool } = require('pg');
const pool = new Pool({...});

const resolvers = {
  Query: {...}
  Mutation: {
    ...
    addEvaluator: async (_, { input }) => {
    const { name, profession, performanceExp, appExp, agExp, evaluationDate } = input;
    const values = [name, profession, performanceExp, appExp, agExp, evaluationDate];
    const query = 'INSERT INTO tb_evaluator (name, profession, performance_exp, app_exp, ag_exp, evaluation_date) VALUES ($1, $2, $3, $4, $5, $6) RETURNING *';

    try {
      const result = await pool.query(query,values);
      return result.rows[0];
    } catch (error) {
      console.error('Error adding evaluation:', error);
      throw new Error('Failed to add evaluation');
    }
  }
}};

当我启动服务器时,我会进入 apollo 服务器沙箱并执行此操作:

mutation Mutation($input: AddEvaluatorInput!) {
  addEvaluator(input: $input) {
    id
    name
    profession
    performanceExp
    appExp
    agExp
    evaluationDate
  }
}

在变量选项卡中我设置了这些值:

{
  "input": {
    "agExp": "a",
    "appExp": "b",
    "evaluationDate": "c",
    "name": "d",
    "performanceExp": "e",
    "profession": "f"
  }
}

但是当我运行它时,我收到此错误

"errors": [
   {
     "message": "Cannot return null for non-nullable field Evaluator.performanceExp.",
     "locations": [
       {
         "line": 6,
         "column": 5
       }
     ],
     "path": [
       "addEvaluator",
       "performanceExp"
     ],

但是,除了错误之外,数据仍然插入到我的 pg 数据库中,所以我不知道我是否只是忽略了这个错误,或者我是否做错了什么,因为我还有其他非常相似的突变,并且唯一的区别是参数的数量。顺便说一句,当我使用这些变量:performanceExp、appExp、agExp 和 evaluationDate 时,或者当我在代码中静态设置其值时,它运行时没有错误,

reactjs node.js graphql react-apollo apollo-server
1个回答
0
投票

在突变结束时,您在数据库中查询刚刚插入的记录:

const result = await pool.query(query,values);
return result.rows[0];

但是,您无法将

snake_case
列名称转换回
camelCase
- 结果,您的
performanceExp, appExp,
agExp
字段将全部为空,因为 GraphQL 服务器会从之前的结果记录中丢弃
performance_exp
等...创建 JSON 数据集以发送回客户端。

© www.soinside.com 2019 - 2024. All rights reserved.