From 52bdccd4d19dee2b944d255fde3b2d21ce1c77b1 Mon Sep 17 00:00:00 2001 From: Leon Xu Date: Sat, 30 Dec 2023 17:21:13 -0800 Subject: [PATCH] file & create: created cron job to api/cron --- app/api/cron/route.ts | 78 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 app/api/cron/route.ts diff --git a/app/api/cron/route.ts b/app/api/cron/route.ts new file mode 100644 index 0000000..34c564e --- /dev/null +++ b/app/api/cron/route.ts @@ -0,0 +1,78 @@ +import { NextResponse } from "next/server"; + +import { getLowestPrice, getHighestPrice, getAveragePrice, getEmailNotifType } from "@/lib/utils"; +import { connectToDB } from '@/lib/mongoose'; +import Product from '@/lib/models/product.model'; +import { scrapeAmazonProduct } from '@/lib/scraper'; +import { generateEmailBody, sendEmail } from "@/lib/nodemailer"; + +export const maxDuration = 300; // This function can run for a maximum of 300 seconds +export const dynamic = "force-dynamic"; +export const revalidate = 0; + + +export async function GET() { + try { + connectToDB(); + + const products = await Product.find({}); + + if (!products) throw new Error('No product found'); + + // 1. Scrape latest product details & update DB. + const updatedProducts = await Promise.all( + products.map(async (currentProduct) => { + const scrapedProduct = await scrapeAmazonProduct(currentProduct.url); + + if (!scrapedProduct) throw new Error('No product found'); + + const updatedPriceHistory = [ + ...currentProduct.priceHistory, + { price: scrapedProduct.currentPrice } + ] + + const product = { + ...scrapedProduct, + priceHistory: updatedPriceHistory, + lowestPrice: getLowestPrice(updatedPriceHistory), + highestPrice: getHighestPrice(updatedPriceHistory), + averagePrice: getAveragePrice(updatedPriceHistory) + } + + const updatedProduct = await Product.findOneAndUpdate({ + url: scrapedProduct.url + }, + product + ); + + // 2. CHECK EACH PRODUCT'S STATUS & SEND EMAIL ACCORDINGLY + const emailNotifType = getEmailNotifType( + scrapedProduct, + currentProduct + ); + + if (emailNotifType && updatedProduct.users.length > 0) { + const productInfo = { + title: updatedProduct.title, + url: updatedProduct.url, + }; + // Construct emailContent + const emailContent = await generateEmailBody(productInfo, emailNotifType); + // Get array of user emails + const userEmails = updatedProduct.users.map((user: any) => user.email); + // Send email notification + await sendEmail(emailContent, userEmails); + } + + return updatedProduct; + }) + ); + + return NextResponse.json({ + message: "Ok", + data: updatedProducts, + }); + } catch (error: any) { + throw new Error(`Failed to get all products: ${error.message}`) + } +} \ No newline at end of file