-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
81 lines (67 loc) · 1.82 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
'user strict';
require('dotenv').config();
const express = require('express');
const mongoose = require('mongoose');
const morgan = require('morgan');
const passport = require('passport');
const cors = require('cors');
const app = express();
const { localStrategy, jwtStrategy } = require('./auth/strategies');
const authRouter = require('./auth/router');
const { PORT, DATABASE_URL } = require('./config');
const usersRouter = require('./users-router');
const searchesRouter = require('./searches-router');
app.use(cors());
app.use(morgan('common'));
app.use(express.static('public'));
app.use(express.json());
app.get('/', (req, res) => {
res.sendFile(__dirname + '/public/index.html');
});
// passport auth strategies
passport.use(localStrategy);
passport.use(jwtStrategy);
app.use('/users', usersRouter);
app.use('/searches', searchesRouter);
app.use('/auth', authRouter);
// catch-all endpoint if client makes request to non-existent endpoint
app.use('*', function (req, res) {
res.status(404).json({ message: 'Not Found' });
});
let server;
function runServer(databaseUrl, port = PORT) {
return new Promise((resolve, reject) => {
console.log('Starting Server')
mongoose.connect(databaseUrl, err => {
if (err) {
return reject(err);
}
})
server = app
.listen(port, () => {
console.log(`Your app is listening on port ${port}`);
resolve();
})
.on("error", err => {
mongoose.disconnect();
reject(err);
});
});
}
function closeServer() {
return mongoose.disconnect().then(() => {
return new Promise((resolve, reject) => {
console.log('Closing Server');
server.close(err => {
if (err) {
return reject(err);
}
resolve();
});
});
});
}
if (require.main === module) {
runServer(DATABASE_URL).catch(err => console.error(err));
}
module.exports = { app, runServer, closeServer };