From 6000aea35053e33b8ab415312cb572260624dfb6 Mon Sep 17 00:00:00 2001 From: Meirbek-dev Date: Mon, 16 Dec 2024 19:54:05 +0500 Subject: [PATCH] added caching and improved error handling for get-total-revenue action --- actions/get-total-revenue.ts | 70 +++++++++++++++++++++++++----------- 1 file changed, 50 insertions(+), 20 deletions(-) diff --git a/actions/get-total-revenue.ts b/actions/get-total-revenue.ts index c8e59e4..2181783 100644 --- a/actions/get-total-revenue.ts +++ b/actions/get-total-revenue.ts @@ -1,25 +1,55 @@ +import { cache } from 'react'; +import { z } from 'zod'; + import prismadb from '@/lib/prismadb'; -export const getTotalRevenue = async (storeId: string) => { - const paidOrders = await prismadb.order.findMany({ - where: { - storeId, - isPaid: true, - }, - include: { - orderItems: { - include: { - product: true, +const storeIdSchema = z.string().uuid('Неверный формат идентификатора магазина'); + +interface PrismaOrder { + orderItems: { + product: { + price: number; + }; + }[]; +} + +// Кэшированная функция получения выручки +export const getTotalRevenue = cache(async (storeId: string) => { + try { + const validationResult = storeIdSchema.safeParse(storeId); + + if (!validationResult.success) { + throw new Error('Неверный идентификатор магазина'); + } + + const paidOrders = await prismadb.order.findMany({ + where: { + storeId: validationResult.data, + isPaid: true, + }, + select: { + orderItems: { + select: { + product: { + select: { + price: true, + }, + }, + }, }, }, - }, - }); + }); - return paidOrders.reduce((total: any, order: any) => { - const orderTotal = order.orderItems.reduce( - (orderSum: any, item: any) => orderSum + item.product.price.toNumber(), - 0, - ); - return total + orderTotal; - }, 0); -}; + return paidOrders.reduce((total: number, order: PrismaOrder) => { + const orderTotal = order.orderItems.reduce( + (orderSum: number, item) => + orderSum + item.product.price, + 0, + ); + return total + orderTotal; + }, 0); + } catch (error) { + console.error('[GET_TOTAL_REVENUE]', error); + return 0; + } +});