file & create: created cron job to api/cron
This commit is contained in:
1 parent
d1fa3565e2
commit
52bdccd4d1
1 file changed
+78
@@ -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}`)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user