77 lines
1.9 KiB
JavaScript
77 lines
1.9 KiB
JavaScript
let fetch = require("node-fetch");
|
|
let cheerio = require("cheerio");
|
|
let express = require("express");
|
|
const path = require("path");
|
|
const bodyParser = require("body-parser");
|
|
const MarketAlert = require("./MarketAlert");
|
|
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/:url", async (req, res) => {
|
|
let url =
|
|
"https://www.olx.ba/pretraga?" +
|
|
req.params.url +
|
|
"&sort_order=desc&sort_po=datum";
|
|
let appts = [];
|
|
response = await fetch(url);
|
|
const body = await response.text();
|
|
|
|
const $ = cheerio.load(body);
|
|
|
|
$("#rezultatipretrage")
|
|
.find(".listitem")
|
|
.each(async (index, elem) => {
|
|
if (index == 0) {
|
|
lastItemDate = $(elem)
|
|
.find(".cijena > .datum > div")
|
|
.first()
|
|
.attr("data-cijelidatum");
|
|
}
|
|
const id = $(elem)
|
|
.find("a")
|
|
.first()
|
|
.attr("href");
|
|
const cijena = $(elem)
|
|
.find(".cijena > .datum > span")
|
|
.first()
|
|
.text();
|
|
const image = $(elem)
|
|
.find("a > .slika > img")
|
|
.first()
|
|
.attr("src");
|
|
appts.push({ url: id, price: cijena, image });
|
|
});
|
|
const [dan, mjesec, godina] = lastItemDate
|
|
.split(". u ")[0]
|
|
.split(".")
|
|
.map(el => Number(el));
|
|
const [sati, minute] = lastItemDate
|
|
.split(". u ")[1]
|
|
.split(":")
|
|
.map(el => Number(el));
|
|
last_date = String(new Date(godina, mjesec, dan, sati, minute));
|
|
res.json({
|
|
last_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}!`));
|