-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
97 lines (78 loc) · 2.47 KB
/
server.js
File metadata and controls
97 lines (78 loc) · 2.47 KB
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
// Include Server Dependencies
var express = require("express");
var bodyParser = require("body-parser");
var logger = require("morgan");
var mongoose = require("mongoose");
// Require History Schema
var History = require("./models/History");
// Create Instance of Express
var app = express();
// Sets an initial port. We'll use this later in our listener
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"));
// -------------------------------------------------
// Connect to localhost if not a production environment
if(process.env.MONGODB_URI) {
// Gotten using `heroku config | grep MONGODB_URI` command in Command Line
mongoose.connect(process.env.MONGODB_URI);
}
else{
mongoose.connect('mongodb://localhost/test');
// mongoose.connect(databaseUri);
}
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("/", function(req, res) {
res.sendFile(__dirname + "/public/index.html");
});
// This is the route we will send GET requests to retrieve our most recent search data.
// We will call this route the moment our page gets rendered
app.get("/api", function(req, res) {
// We will find all the records, sort it in descending order, then limit the records to 5
History.find({}).sort([
["date", "descending"]
]).limit(5).exec(function(err, doc) {
if (err) {
console.log(err);
}
else {
res.send(doc);
}
});
});
// This is the route we will send POST requests to save each search.
app.post("/api", function(req, res) {
console.log("BODY: " + req.body);
// Here we'll save the location based on the JSON input.
// We'll use Date.now() to always get the current date time
History.create({
title: req.body.title,
url: req.body.url,
date: Date.now()
}, function(err) {
if (err) {
console.log(err);
}
else {
res.send("Saved Search");
}
});
});
// -------------------------------------------------
// Listener
app.listen(PORT, function() {
console.log("App listening on PORT: " + PORT);
});