-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserver.js
97 lines (74 loc) · 2.33 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
// server.js
/* ================== SETUP ================== */
require('dotenv').config();
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const cors = require('cors');
const mongoose = require('mongoose');
const http = require('http');
const path = require('path');
const search = require('./search');
const searchTerm = require('./models/searchTerm');
app.use(bodyParser.json());
app.use(cors());
/* ================== DB CONNECTION ================== */
const MONGODB_URI = `mongodb://${process.env.USER}:${process.env.PASS}@${process.env.HOST}:${process.env.DB_PORT}/${process.env.DB}`;
// connect to DB if running locally:
// mongoose.connect('mongodb://localhost/searchTerms');
// connect to mLab
mongoose.connect(MONGODB_URI);
mongoose.Promise = global.Promise;
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB connection error:'));
/* ================== ROUTES ================== */
// get all UNIQUE search terms stored in DB, sorted by most recent date
app.get('/api/recent', (req, res, next) => {
searchTerm.aggregate(
[
{ "$group": {
_id: "$searchVal",
doc: {$first: "$$ROOT"}
}},
{ "$sort": { "searchDate": -1 } },
],
(err, data) => {
if (err) {
console.log(err);
res.send(err);
}
console.log(data);
res.json(data);
}
);
});
// new image search
app.get('/api/search/:searchVal*', (req, res, next) => {
const { searchVal } = req.params;
const { offset } = req.query;
const data = new searchTerm({
searchVal,
searchDate: new Date()
});
data.save(err => {
if (err) {
console.log(`Error Saving to database: ${err}`);
}
});
search(searchVal, offset, (data) => {
const baseUrl = `${req.protocol}://${req.get('host')}${req.baseUrl}${req.path}`;
data.baseUrl = baseUrl;
res.json(data);
});
});
// set static path
app.use(express.static(path.join(__dirname, '/client/build/')));
app.get('/', (req, res) => {
console.log('root route, serving client');
res.status(200)
.sendFile(path.join(__dirname, '../client/build/index.html'));
});
const server = http.createServer(app);
const port = process.env.PORT || 8080;
app.set('port', port);
server.listen(port, () => console.log(`Server listening on localhost:${port}`));