-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
added caching and improved error handling for get-total-revenue action
- Loading branch information
1 parent
123e10c
commit 6000aea
Showing
1 changed file
with
50 additions
and
20 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} | ||
}); |