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.

This commit is contained in:
Leon Xu committed 2023-12-30 14:06:23 -08:00
1 parent 9b3c05f831
commit f8991b8709
1 file changed
+38 -2
+38 -2
View File
@@ -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}`)
}