【问题标题】:How to deal with readonly arguments from DataLoader - (GraphQL + Apollo in NextJS)如何处理来自 DataLoader 的只读参数 -(NextJS 中的 GraphQL + Apollo)
【发布时间】:2020-06-20 21:20:03
【问题描述】:

我有一个加载器函数来从数据库中获取厨师。所以这个加载器会收到一个ids 的数组,奇怪的是ids 有一个readonly 类型。

当我尝试将该只读类型传递给数据库查询时,它会报错。

如何修复类型定义?

源码:https://github.com/LauraBeatris/graphql-with-nextjs/blob/master/pages/api/loader.ts

【问题讨论】:

  • 根据错误,值"id" 不是您调用的whereIn 方法的有效参数。此方法特定于您用于创建 databaseClient 的任何库(我猜是 Knex)——所以这个问题并不是 DataLoader 或 GraphQL 所特有的。
  • 由于 DataLoader 的批量加载函数使用泛型类型,您可能需要为您的 ids 参数显式提供类型(即 ids: string[])。我猜没有这个,TypeScript 无法正确匹配 whereIn 的正确重载签名。

标签: graphql apollo apollo-client dataloader


【解决方案1】:

我根据@DanielRearden 的评论修复了这个问题。

DataLoader 实例接收的函数使用泛型类型,因此我们能够将类型传递给ids 参数,然后在whereIn knex 方法中使用它。

 new DataLoader((ids: string[]) => (
    databaseClient
      .table("chefs")
      .whereIn("id", ids)
      .select("*")
      .then(rows => ids.map(id => rows.find(row => row.id === id)))
  ))

【讨论】:

    猜你喜欢
    • 2020-08-04
    • 2020-12-14
    • 2019-10-09
    • 2020-10-16
    • 2017-06-23
    • 2019-11-17
    • 2018-09-14
    • 2018-01-28
    • 2016-12-12
    相关资源
    最近更新 更多