Home > Software engineering >  dynamic sorting in prisma and typed queries
dynamic sorting in prisma and typed queries

Time:09-12

I'm trying to define a query in prisma at runtime, but getting stuck at the first hurdle.

so this works:

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

but when I try to separately define the query I get TS errors.

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

those two things should be identical? but somewhere deep in prisma's maze of automagically generated code...

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'.

from Type 'string' is not assignable to type 'SortOrder | undefined'. I thought maybe I can just pass orderBy: 'name' but that fails too.

FWIW if i @ts-ignore the code works, but if prisma typechecking has to be ignored, then it serves little purpose.

my next step after that is to try to dynamically compose the orderBy from passed in parameters, but I need to get the basics above to work first.

Can someone suggest why this typechecking of prisma fails?

CodePudding user response:

You can use these workarounds -

  1. Wrap the orderBy with as const to stop typescript from inferring the order as string.
  2. Use Prisma.orderBy.asc instead of "asc".
  • Related