From f8991b870917eddaee530bbdd9e049742a3d3373 Mon Sep 17 00:00:00 2001 From: Leon Xu Date: Sat, 30 Dec 2023 14:06:23 -0800 Subject: [PATCH] doc: added scrapedProduct to see if there's anyone of them are in the database, if there isn't, we created it. If it is there, we just updated the revalent price. --- lib/actions/index.ts | 40 ++++++++++++++++++++++++++++++++++++++-- 1 file changed, 38 insertions(+), 2 deletions(-) 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}`) }