javascriptbackendprisma

Prisma find many and count in one request


I have a pagination in my category service, and I have to return obj with total count of categories and data

But there's can be some parameters. As example, I should return categories that was created by certain user:

async findAll(
    { onlyParents }: ParamsCategoryDto,
    user: ITokenPayload | undefined,
): Promise<IFilterRes> {
    const categories = await this.prisma.category.findMany({
      where: {
        user_id: user?.id,
      },
    });

    return {
      pagination: {
        total: this.prisma.category.count({
          where: { // <- duplicate
          user_id: user?.id,
        },
      }),
    },
    data: categories,
  };
}

I should duplicate where in both query. Which is not very nice. Is there any option to do it in one request.

P.S. I can make some var for where, but in this way I lose typification, which I also don't like.


Solution

  • This is my example code to acheive it with a single transaction, no duplicate code and not losing type autocomplete

    import { Prisma } from '@prisma/client';
    import { PrismaClient } from '@prisma/client'
    const prisma = new PrismaClient()
    
    const findAll = async (userId: String) => {
      const query: Prisma.categoriesFindManyArgs = {
        where: {
          user_id: userId,
        }
      };
      const [categories, count] = await prisma.$transaction([
        prisma.categories.findMany(query),
        prisma.categories.count({ where: query.where })
      ]);
    
      return {
        pagination: {
          total: count
        },
        data: categories
      };
    };