61 lines
1.7 KiB
JavaScript
61 lines
1.7 KiB
JavaScript
let express = require("express");
|
|
const path = require("path");
|
|
const bodyParser = require("body-parser");
|
|
const MarketAlert = require("./MarketAlert");
|
|
const sendNotification = require("./utils/sendnotification");
|
|
const scrapTheItems = require("./utils/scraptheitems");
|
|
const sequelize = require("./db.js");
|
|
|
|
const app = express();
|
|
app.use(bodyParser.json());
|
|
app.use(bodyParser.urlencoded({ extended: true }));
|
|
|
|
const port = process.env.PORT || 5000;
|
|
|
|
app.get("/api/sendnotifications", async function(req, res) {
|
|
let marketAlerts = await MarketAlert.findAll();
|
|
|
|
let lastDateUpdate = await Promise.all(
|
|
marketAlerts
|
|
.map(marketAlert => {
|
|
const { id, email, olx_url, last_date } = marketAlert.dataValues;
|
|
return { id, email, olx_url, last_date };
|
|
})
|
|
.map(sendNotification)
|
|
);
|
|
if (lastDateUpdate.some(dateUpdate => !dateUpdate)) return;
|
|
lastDateUpdate.length &&
|
|
lastDateUpdate.forEach(dateUpdate =>
|
|
MarketAlert.update(
|
|
{ last_date: dateUpdate.date },
|
|
{ where: { id: dateUpdate.id } }
|
|
)
|
|
);
|
|
});
|
|
|
|
app.get("/api/:url", async (req, res) => {
|
|
let url =
|
|
"https://www.olx.ba/pretraga?" +
|
|
req.params.url +
|
|
"&sort_order=desc&sort_po=datum";
|
|
let appts = scrapTheItems(url);
|
|
res.json({
|
|
last_date: appts[0] && appts[0].date,
|
|
items: appts
|
|
});
|
|
});
|
|
|
|
app.post("/api/marketalerts", function(req, res) {
|
|
const { email, last_date, olx_url } = req.body;
|
|
sequelize.sync().then(() =>
|
|
MarketAlert.create({
|
|
olx_url,
|
|
last_date,
|
|
email
|
|
})
|
|
);
|
|
res.json({ message: "Market Alert Created!" });
|
|
});
|
|
|
|
app.listen(port, () => console.log(`Example app listening on port ${port}!`));
|