-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
69 lines (58 loc) · 1.88 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
'use strict';
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const apartments = require('./model/CraigslistApt');
const MongoClient = require('mongodb').MongoClient;
const port = process.env.PORT || 5000;
const app = express();
/* DATABASE CONFIG */
const dbUrl = require('./config/keys').mongoURI;
const dbArray = dbUrl.split('/');
const dbName = dbArray[dbArray.length - 1];
/* MIDDLEWARE SHIT */
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
/* CONNECT TO MONGO.DB (MONGO ATLAS) */
mongoose
.connect(dbUrl, { useNewUrlParser: true })
.then(() => console.log('Connected to Mongo'))
.catch(error => console.log(error));
/* OPEN (OR RE-USE) A CONNECTION TO THE DB AND RETURN MONGODB CLIENT */
async function theClient() {
console.log('calling client');
console.log(`Connecting to ${dbUrl}...`);
if (connection) {
return connection;
} else {
connection = await MongoClient.connect(dbUrl, { useNewUrlParser: true });
console.log('Connected to database.');
return connection;
}
}
async function cApartments() {
const client = await theClient();
const db = client.db(dbName);
const apartments = db.collection('craigslistapts');
return apartments;
}
async function all() {
let results = await apartments();
return results.find({}).sort([['timestamp', 1]]);
}
const main_router = express.Router();
main_router.use(function(req, res, next) {
console.log('Something');
next();
});
main_router.get('/', function(req, res) {
res.json({ message: 'Fuck' });
});
app.use('/', main_router);
app.get('/test/craigslistapts', async (request, response, closeConnection) => {
const results = await apartments();
console.log(`Sending ${results.length} results`);
response.send(results);
closeConnection();
});
app.listen(port, () => console.log(`FUCKING FUCK FUCK ${port}`));