diff --git a/lib/actions/index.ts b/lib/actions/index.ts index 31f843e..21390d1 100644 --- a/lib/actions/index.ts +++ b/lib/actions/index.ts @@ -1,11 +1,47 @@ 'use server' +import { revalidatePath } from 'next/cache'; import { scrapeAmazonProduct } from "../scraper"; +import { connectToDB } from '../mongoose'; +import Product from '../models/product.model' +import { getAveragePrice, getHighestPrice, getLowestPrice } from "../utils"; export async function scrapeAndStoreProduct(productUrl: string) { - if(!productUrl) return; + if (!productUrl) return; try { - const scrapedProudct = await scrapeAmazonProduct(productUrl) + // Store it in the DB + connectToDB(); + const scrapedProduct = await scrapeAmazonProduct(productUrl); + if (!scrapedProduct) return; + + let product = scrapedProduct; + + const existingProduct = await Product.findOne({ url: scrapedProduct.url }); + + if (existingProduct) { + const updatedPriceHistory: any = [ + ...existingProduct.priceHistory, + { price: scrapedProduct.currentPrice } + ] + + product = { + ...scrapedProduct, + priceHistory: updatedPriceHistory, + lowestPrice: getLowestPrice(updatedPriceHistory), + highestPrice: getHighestPrice(updatedPriceHistory), + averagePrice: getAveragePrice(updatedPriceHistory) + } + } + + const newProduct = await Product.findOneAndUpdate({ + url: scrapedProduct.url + }, + product, + { upsert: true, new: true } + ); + + revalidatePath(`/products/${newProduct._id}`); + } catch (error: any) { throw new Error(`Failed to create/update product; ${error.message}`) }