-
Notifications
You must be signed in to change notification settings - Fork 1
/
app.js
52 lines (47 loc) · 1.81 KB
/
app.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
require('dotenv').config();
const express = require('express');
const app = express();
const Nightmare = require('nightmare'); //nightmare will help to find the url and price value in the url block
const nightmare = Nightmare();
const port = process.env.port || 3000;
const sgMail = require('@sendgrid/mail');
app.use(express.urlencoded({ extended: false }));
app.use(express.json());
let SENDGRID_API_KEY = process.env.SENDGRID_API_KEY;
sgMail.setApiKey(SENDGRID_API_KEY);
function sendEmail(userEmail, url, price) {
let message = {
to: userEmail,
from: 'shubhamank002@gmail.com',
subject: 'Price has dropped',
text: `The price on ${url} has dropped below ${price}`,
html: `<strong>The price on ${url} has dropped below ${price}</strong>`,
}
return sgMail.send(message);
}
const checkPrice = async (url, price, userEmail) => {
try {
let priceInString = await nightmare
.goto(url)
.wait('#priceblock_ourprice')
.evaluate(() => document.querySelector('#priceblock_ourprice').innerText)
.end();
let priceInValue = parseFloat(priceInString.replace('₹', ''));
if (priceInValue < price) {
console.log(`New Price: ${price}`);
console.log(`Actual Price: ${priceInValue}`);
await sendEmail(userEmail, url, price);
console.log('Email has been sent');
}
else {
console.log('Price is still higher');
}
} catch (err) {
console.log(err);
}
}
app.post('/products', (req, res) => {
console.log(req.body.email + ' sent a request');
checkPrice(req.body.prodUrl, req.body.price, req.body.email);
});
app.listen(port, () => console.log(`Server listening on port ${port}`));