带有Knex.js的数据加载器

时间:2019-11-19 06:50:45

标签: javascript node.js typescript 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

1 个答案:

答案 0 :(得分:1)

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']])

希望有帮助,
最好的问候