forked from mrwyndham/fastpocket
47 lines
1.7 KiB
TypeScript
47 lines
1.7 KiB
TypeScript
"use server";
|
|
|
|
import { Product, Price } from "@/types";
|
|
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/actions","productResponse",productResponse)
|
|
const unsortedProducts: Product[] = productResponse.items;
|
|
console.log("app/pricing/actions","unsortedProducts",unsortedProducts)
|
|
const prices = await pb.collection("price").getFullList<Price>();
|
|
console.log("app/pricing/actions","prices",prices)
|
|
for (const product of unsortedProducts) {
|
|
product.metadata.benefits = product?.metadata?.benefits ? JSON.parse(product.metadata.benefits as any) : [];
|
|
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: Product, b: Product) => a.product_order - b.product_order)
|
|
return sortedProducts;
|
|
} catch (error) {
|
|
console.log(error);
|
|
return [];
|
|
}
|
|
} |