forked from mrwyndham/fastpocket
52 lines
1.6 KiB
JavaScript
52 lines
1.6 KiB
JavaScript
"use server"
|
|
import pb from "@/lib/pocketbase"
|
|
|
|
export async function apiPrices() {
|
|
try {
|
|
const pocketbaseUrl = process.env.NEXT_PUBLIC_POCKETBASE_URL
|
|
if (!pocketbaseUrl) {
|
|
throw Error("Connection Timeout")
|
|
}
|
|
const productRequest = await fetch(
|
|
`${pocketbaseUrl}/api/collections/product/records?filter=(active=true)`,
|
|
{
|
|
cache: "no-cache",
|
|
method: "GET",
|
|
headers: {
|
|
"Content-Type": "application/json"
|
|
}
|
|
}
|
|
)
|
|
const productResponse = await productRequest.json()
|
|
console.log("app/pricing/action", "productResponse", productResponse)
|
|
const unsortedProducts = productResponse.items
|
|
console.log("app/pricing/action", "unsortedProducts", unsortedProducts)
|
|
const prices = await pb.collection("price").getFullList()
|
|
console.log("app/pricing/action", "prices", prices)
|
|
for (const product of unsortedProducts) {
|
|
product.metadata.benefits = product?.metadata?.benefits
|
|
? JSON.parse(product.metadata.benefits)
|
|
: []
|
|
const pricesOfProduct = prices.filter(
|
|
price => price.product_id === product.product_id
|
|
)
|
|
for (const priceOfProduct of pricesOfProduct) {
|
|
product.type = priceOfProduct.type
|
|
if (priceOfProduct.interval === "year") {
|
|
product.yearlyPrice = priceOfProduct
|
|
} else {
|
|
product.monthlyPrice = priceOfProduct
|
|
}
|
|
}
|
|
}
|
|
|
|
const sortedProducts = unsortedProducts.sort(
|
|
(a, b) => a.product_order - b.product_order
|
|
)
|
|
return sortedProducts
|
|
} catch (error) {
|
|
console.log(error)
|
|
return []
|
|
}
|
|
}
|