Prisma Transaction Handle

agnusdei·2023년 7월 5일
0
post-custom-banner
async search(option: PaginationInfluencerRequestOptionDTO): Promise<
  [
    InfluencerRequest[],
    number,
    {
      totalCount: number;
      pendingCount: number;
      returnedCount: number;
      completedCount: number;
    }
  ]
> {
  // Define the 'where' condition for filtering
  const where: Prisma.InfluencerRequestWhereInput = {
    content: { contains: option.query },
    deletedAt: null || undefined,
  };

  // Define the 'orderBy' condition for sorting
  const orderBy: Prisma.InfluencerRequestOrderByWithAggregationInput = {};
  orderBy[option.orderBy] = option.align;

  // Group the influencer requests by userId
  const userGroup = await this.prismaService.influencerRequest.groupBy({
    by: ['userId'],
  });

  // Extract the userIds from the grouped data
  const userIds = userGroup.map((group) => group.userId);

  // Fetch influencer requests for each userId
  const influencerRequests = await Promise.all(
    userIds.map(async (userId) => {
      const userRequests = await this.prismaService.influencerRequest.findMany({
        where: {
          ...where,
          userId,
        },
        orderBy,
        include: {
          user: true,
          logs: true,
        },
        take: 1,
      });
      return userRequests[0];
    })
  );

  let filterEntities;
  if (option.status !== 'ALL') {
    // Filter influencer requests based on the provided status option
    filterEntities = influencerRequests.filter(
      (item) => item.status === option.status
    );
  } else {
    // If status is 'ALL', include all influencer requests without filtering
    filterEntities = influencerRequests;
  }

  const count = filterEntities.length;

  const counts = {
    // Calculate the total count and count for each status
    totalCount: filterEntities.length,
    pendingCount: influencerRequests
      .filter((item) => item && item.status === InfluencerRequestStatus.PENDING)
      .filter(Boolean).length,
    returnedCount: influencerRequests
      .filter((item) => item && item.status === InfluencerRequestStatus.RETURN)
      .filter(Boolean).length,
    completedCount: influencerRequests
      .filter((item) => item && item.status === InfluencerRequestStatus.COMPLETED)
      .filter(Boolean).length,
  };

  // Return the filtered influencer requests, count, and counts object
  return [filterEntities, count, counts];
}
post-custom-banner

0개의 댓글