【问题标题】:Cannot pass custom result from resolver to Graphql无法将自定义结果从解析器传递到 Graphql
【发布时间】:2021-01-06 17:38:12
【问题描述】:

我正在尝试使用带有属性的 sequelize 获取数据并将其传递给 graphql。 结果在控制台中很好,但 graphql 查询为属性字段返回 null。

我的解析器

    getUnpayedLessons: async (_, args, { models }) => {
  const { Attendance, Student } = models;
  return await Attendance.findAll({
    include: {
      model: Student,
    },
    where: {
      fk_lessonsSerieId: { [Op.is]: null },
    },
    attributes: ["id", [sequelize.fn("count", sequelize.col("absenceFlag")), "unpayedLessons"]],
    group: ["student.id"],
  });
},

查询

getUnpayedLessons {
  id
  unpayedLessons
  student {
    id
    firstName
    lastName
  }
}

架构

type UnpayedLessons {
  id: Int
  unpayedLessons: Int
  student: Student
  }

extend type Query {
  getUnpayedLessons: [UnpayedLessons]
  }

这是我运行查询时解析器的 console.log

    [
   attendance {
    dataValues: { id: 2, unpayedLessons: 8, student: [student] },
    _previousDataValues: { id: 2, unpayedLessons: 8, student: [student] },
    _changed: Set {},
    _options: {
      isNewRecord: false,
     _schema: null,
     _schemaDelimiter: '',
      include: [Array],
      includeNames: [Array],
      includeMap: [Object],
      includeValidated: true,
      attributes: [Array],
      raw: true
     },
]

来自graphql

    {
  "data": {
    "getUnpayedLessons": [
      {
        "id": 2,
        "unpayedLessons": null,
        "student": {
          "id": 2,
          "__typename": "Student"
        },
        "__typename": "UnpayedLessons"
      },
     ]
    }
   }

知道如何将 unpayedLessons 传递给 graphql 吗?

【问题讨论】:

    标签: graphql sequelize.js apollo


    【解决方案1】:

    要调试它,您需要检查从 DB 返回的内容,形状:

    const values = await Attendance.findAll({...
    console.log( values );
    // adapt structure to match query requirements
    // finally return
    return values;
    

    【讨论】:

    • 我的错,实际上控制台中的结果( [attendance { datavalues { ... )就是这样。为了清楚起见,我在这里更改了解析器,但我有你在现实中描述的 console.log。在我看来,DataValues 的形状与我的查询相同。没有?
    • DataValues 不是所需查询结果的一部分 - UnpayedLessons 类型的数组...转换/适应所需的形状
    • 谢谢你,让它工作!但不是很清楚为什么。或者更好的是为什么以前不工作。只是自定义属性没有通过,而且我不放自定义属性时也是一样的形状,从来没有任何问题...
    • IDK ... 嗯,squelize 并不是为了满足 apollo 而设计的,但可能 apollo 可以/已经适应一些**常见**/可能的数据结构 [从 libs/DB/ 返回adapters] 并且能够将它们与所需的返回类型匹配 - 并非所有用例
    猜你喜欢
    • 1970-01-01
    • 2021-12-22
    • 2020-06-13
    • 2020-10-04
    • 1970-01-01
    • 2020-02-21
    • 1970-01-01
    • 1970-01-01
    • 2019-10-24
    相关资源
    最近更新 更多