网站搜索

typescript - 在 Prisma 和类型化查询中进行动态排序


我正在尝试在运行时在 Prisma 中定义一个查询,但在第一个障碍就卡住了。

所以这个有效:

  const items = await prisma.styleTags.findMany({
    orderBy: {
      name: 'asc',
    }
  });

但是当我尝试单独定义查询时,我会得到 TS 错误。

  const orderBy = {
    cname: 'asc',
  }
  const items2 = await prisma.styleTags.findMany({
    orderBy
  });

那两件东西应该是相同的?但是在Prisma那迷宫般自动生成的代码深处的某个地方...

Type '{ cname: string; priority: string; }' is not assignable to type 'Enumerable<StyleTagsOrderByWithRelationInput> | undefined'.
  Type '{ cname: string; priority: string; }' is not assignable to type 'StyleTagsOrderByWithRelationInput'.
    Types of property 'cname' are incompatible.
      Type 'string' is not assignable to type 'SortOrder | undefined'.

从 Type 'string' is not assignable to type 'SortOrder | undefined'. 我以为我可以直接传 orderBy: 'name',但那也失败了。

仅供参考,如果我 @ts-ignore 代码可以运行,但如果必须忽略 Prisma 的类型检查,那么它的作用就很小。

在那之后,我的下一步是尝试根据传入的参数动态组合orderBy,但我首先需要让上面的基础工作运行起来。

有人能解释一下为什么 Prisma 的这种类型检查会失败吗?

答案#1

你可以使用这些变通方法 -

  1. 将 orderBy 用 as const 包裹,以阻止 typescript 将顺序推断为字符串。
  2. 请使用 Prisma.orderBy.asc 替代 "asc"。

答案#2

这是我的 NextJs API 端点逻辑:

import type { NextApiRequest, NextApiResponse } from 'next';
import prisma from '@/lib/prisma';

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
    const { _page, _limit, _sort, _order} = req.query;
    const limit = +(_limit ?? 20);
    const offset = (+(_page ?? 1) -1 ) * limit;
    const sort = (_sort ?? 'id').toString();
    const order = _order ?? 'asc';

    const orderBy = {[sort]: order};
    const userCount = await prisma.users.count();
    const users = await prisma.users.findMany({
        orderBy,
        skip: offset,
        take: limit
    });

    res.setHeader('Content-Type', 'application/json');
    res.setHeader('x-total-count', userCount);
    res.status(200).json(users);
}

我希望它会有帮助