首页 > 解决方案 > 带有 Knex.js 的数据加载器

问题描述

在我更新到之前,这段代码运行良好dataloader: 2.0.0

const productLoader = new DataLoader(async keys => {
  const products: Product[] = await knex('product')
    .whereIn('id', keys)
    .select()

  const productMap: any = {}

  products.forEach((p: any) => {
    productMap[p.id] = p
  })

  return keys.map((k: any) => productMap[k])
})

export default productLoader

现在它给出了错误:

loader.ts:7:14 - error TS2769: No overload matches this call.
  The last overload gave the following error.
    Argument of type '"id"' is not assignable to parameter of type 'string[]'.

7     .whereIn('id', keys)
               ~~~~

  node_modules/knex/types/index.d.ts:1137:5
    1137     <TRecordInner, TResultInner>(
             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    1138       columnNames: string[],
         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    1139       values: QueryBuilder<TRecordInner, TResultInner>
         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    1140     ): QueryBuilder<TRecord, TResult>;
         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    The last overload is declared here.


Found 1 error.

我做错了什么?

// package.json

"dataloader": "^2.0.0",
"knex": "^0.20.2",

堆栈:Apollo-server-express、TypeScript、Postgres、Knex.js

标签: javascriptnode.jstypescriptknex.js

解决方案


似乎 knex (TypeScript) 期望您将字符串 ( string[]) 数组设置为 的第一个参数whereIn,如下所示:

const products: Product[] = await knex('product')
  .whereIn(['id'], keys)
  .select();

这与在多个列中搜索时相同(以下示例来自 Knex.js 文档):

knex.select('name').from('users')   
  .whereIn(['account_id', 'email'], [[3, 'test3@example.com'], [4, 'test4@example.com']])

希望它有帮助,
最好的问候


推荐阅读