const express = require(
"express"
);
const mongoose = require(
"mongoose"
);
const request = require(
"request"
);
const cheerio = require(
"cheerio"
);
const bodyParser = require(
"body-parser"
);
const exphbs = require(
"express-handlebars"
);
const PORT = process.env.PORT || 3000;
const app = express();
app.use(bodyParser.urlencoded({
extended:
false
}));
app.use(bodyParser.json({
type:
"application/json"
}));
app.use(express.static(
"public"
));
mongoose.Promise = Promise;
const MONGODB_URI = process.env.MONGODB_URI
mongoose.connect(MONGODB_URI);
app.engine(
"handlebars"
, exphbs({
defaultLayout:
"main"
}));
app.set(
"view engine"
,
"handlebars"
);
const db = require(
"./models"
);
app.get(
"/"
,
function
(req, res) {
db.Article.find({
saved:
false
},
function
(error, dbArticle) {
if
(error) {
console.log(error);
}
else
{
res.render(
"index"
, {
articles: dbArticle
});
}
})
})
app.get(
"/scrape"
,
function
(req, res) {
const $ = cheerio.load(html);
$(
"h2"
).each(
function
(i, element) {
const title = $(element).find(
"a"
).text().trim();
console.log(
"title"
, title);
const link = $(element).find(
"a"
).attr(
"href"
);
console.log(
"link"
, link);
if
(title && link) {
db.Article.create({
title: title,
link: link
},
function
(err, inserted) {
if
(err) {
console.log(err);
}
else
{
console.log(inserted);
}
});
console.log(i);
if
(i === 10) {
return
res.sendStatus(200);
}
}
});
});
});
app.get(
"/saved"
,
function
(req, res) {
db.Article.find({
saved:
true
})
.then(
function
(dbArticle) {
res.render(
"saved"
, {
articles: dbArticle
})
})
.
catch
(
function
(err) {
res.json(err);
})
});
app.put(
"/saved/:id"
,
function
(req, res) {
db.Article.findByIdAndUpdate(
req.params.id, {
$set: req.body
}, {
new
:
true
})
.then(
function
(dbArticle) {
res.render(
"saved"
, {
articles: dbArticle
})
})
.
catch
(
function
(err) {
res.json(err);
});
});
app.post(
"/submit/:id"
,
function
(req, res) {
db.Note.create(req.body)
.then(
function
(dbNote) {
let articleIdFromString =
mongoose.Types.ObjectId(req.params.id)
return
db.Article.findByIdAndUpdate(
articleIdFromString, {
$push: {
notes: dbNote._id
}
})
})
.then(
function
(dbArticle) {
res.json(dbNote);
})
.
catch
(
function
(err) {
res.json(err);
});
});
app.get(
"/notes/article/:id"
,
function
(req, res) {
db.Article.findOne({
"_id"
: req.params.id })
.populate(
"notes"
)
.exec(
function
(error, data) {
if
(error) {
console.log(error);
}
else
{
res.json(data);
}
});
});
app.get(
"/notes/:id"
,
function
(req, res) {
db.Note.findOneAndRemove({ _id: req.params.id },
function
(error, data) {
if
(error) {
console.log(error);
}
res.json(data);
});
});
app.listen(PORT,
function
() {
console.log(
"App is running"
);
});