2022-04-19 07:22:53 -05:00
|
|
|
const express = require('express');
|
|
|
|
const app = express();
|
2022-04-26 01:20:42 -05:00
|
|
|
const { MongoClient, ObjectId } = require('mongodb');
|
2022-04-26 05:50:07 -05:00
|
|
|
const request = require('request');
|
|
|
|
const cheerio = require('cheerio');
|
|
|
|
const URL = require('url-parse');
|
2022-04-22 07:13:22 -05:00
|
|
|
|
2022-04-19 07:22:53 -05:00
|
|
|
const port = process.env.PORT || 3001;
|
|
|
|
|
|
|
|
const uri = "mongodb://localhost:27017";
|
|
|
|
|
|
|
|
const client = new MongoClient(uri);
|
|
|
|
|
|
|
|
app.use(express.json());
|
|
|
|
|
|
|
|
app.get('/get', async (req, res) => {
|
|
|
|
const data = await getDoc();
|
|
|
|
res.send(data);
|
|
|
|
});
|
|
|
|
|
2022-04-26 05:50:07 -05:00
|
|
|
app.post('/post', (req, res) => {
|
|
|
|
let title;
|
|
|
|
const pageToVisit = req.body.link;
|
|
|
|
request(pageToVisit, (error, response, body) => {
|
2022-04-27 07:19:47 -05:00
|
|
|
try {
|
|
|
|
if(response.statusCode === 200) {
|
|
|
|
// Parse the document body
|
|
|
|
const $ = cheerio.load(body);
|
2022-04-26 05:50:07 -05:00
|
|
|
|
2022-04-27 07:19:47 -05:00
|
|
|
req.body.title = $('title').text();
|
|
|
|
insertDoc(req.body);
|
|
|
|
} else {
|
|
|
|
req.body.title = null;
|
|
|
|
insertDoc(req.body);
|
|
|
|
}
|
|
|
|
} catch (error) {
|
|
|
|
console.log(error);
|
|
|
|
req.body.title = null;
|
|
|
|
insertDoc(req.body);
|
|
|
|
}
|
2022-04-26 05:50:07 -05:00
|
|
|
});
|
2022-04-19 07:22:53 -05:00
|
|
|
});
|
|
|
|
|
2022-04-26 01:20:42 -05:00
|
|
|
app.delete('/delete', async (req, res) => {
|
|
|
|
const id = req.body.id.toString();
|
|
|
|
|
|
|
|
await deleteDoc(id);
|
|
|
|
|
|
|
|
res.send(`Bookmark with ObjectId "${id}" deleted.`);
|
|
|
|
});
|
|
|
|
|
2022-04-19 07:22:53 -05:00
|
|
|
async function insertDoc(doc) {
|
|
|
|
try {
|
|
|
|
const database = client.db("sample_db");
|
|
|
|
const list = database.collection("list");
|
|
|
|
const result = await list.insertOne(doc);
|
|
|
|
}
|
|
|
|
|
|
|
|
catch(err) {
|
|
|
|
console.log(err);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
async function getDoc() {
|
|
|
|
try {
|
|
|
|
const database = client.db("sample_db");
|
|
|
|
const list = database.collection("list");
|
|
|
|
const result = await list.find({}).toArray();
|
|
|
|
|
|
|
|
return result;
|
|
|
|
}
|
|
|
|
|
|
|
|
catch(err) {
|
|
|
|
console.log(err);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-04-26 01:20:42 -05:00
|
|
|
async function deleteDoc(doc) {
|
|
|
|
try {
|
|
|
|
const database = client.db("sample_db");
|
|
|
|
const list = database.collection("list");
|
|
|
|
const result = await list.deleteOne({"_id": ObjectId(doc)});
|
|
|
|
}
|
|
|
|
|
|
|
|
catch(err) {
|
|
|
|
console.log(err);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-04-19 07:22:53 -05:00
|
|
|
app.listen(port, () => {
|
|
|
|
console.log(`Success! running on port ${port}.`);
|
2022-04-26 15:30:36 -05:00
|
|
|
client.connect();
|
2022-04-19 07:22:53 -05:00
|
|
|
});
|