-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
101 lines (77 loc) · 2.17 KB
/
server.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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
// Include Server Dependencies
var express = require("express");
var bodyParser = require("body-parser");
var logger = require("morgan");
var mongoose = require("mongoose");
var cors = require('cors');
// Require schemas
//var Click = require("./models/click");
var Article = require("./models/Article");
var app = express();
app.options('*', cors());
var PORT = process.env.PORT || 3000;
// Run Morgan for Logging
app.use(logger("dev"));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.text());
app.use(bodyParser.json({ type: "application/vnd.api+json" }));
app.use(express.static("./public"));
// -------------------------------------------------
// MongoDB configuration (Change this URL to your own DB)
if (process.env.MONGODB_URI) {
mongoose.connect(process.env.MONGODB_URI)
} else {
mongoose.connect("mongodb://localhost/nyt")
}
var db = mongoose.connection;
db.on("error", function(err) {
console.log("Mongoose Error: ", err);
});
db.once("open", function() {
console.log("Mongoose connection successful.");
});
// -------------------------------------------------
// Main "/" Route. This will redirect the user to our rendered React application
app.get("/api/saved", function(req, res) {
Article.find({}).exec(function(err, doc) {
if (err) {
console.log(err);
} else {
res.json(doc);
}
});
});
app.post("/api/saved", function(req, res) {
let {headline, web_url, pub_date} = req.body;
Article.create({
title: headline.main,
url: web_url,
date: pub_date
}, function(err) {
if (err) {
console.log(err);
} else {
res.send("Saved Search");
}
});
});
app.delete("/api/saved", function(req, res){
console.log("REQ", req.query.articleID);
const id = req.query.articleID;
Article.findByIdAndRemove(id, function(err){
if (err) {
console.log(err);
} else {
res.send("deleted item");
}
});
});
app.get("*", function(req, res) {
res.sendFile("/public/index.html");
});
// -------------------------------------------------
// Starting our express server
app.listen(PORT, function() {
console.log("App listening on PORT: " + PORT);
});