Skip to content

Commit

Permalink
added caching and improved error handling for get-total-revenue action
Browse files Browse the repository at this point in the history
  • Loading branch information
Meirbek-dev committed Dec 16, 2024
1 parent 123e10c commit 6000aea
Showing 1 changed file with 50 additions and 20 deletions.
70 changes: 50 additions & 20 deletions actions/get-total-revenue.ts
Original file line number Diff line number Diff line change
@@ -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;
}
});

0 comments on commit 6000aea

Please sign in to comment.