-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
64 lines (55 loc) · 1.58 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
const fs = require('fs');
const path = require('path');
const cors = require('cors');
const express = require('express');
const mongoose = require('mongoose');
const sassMiddleware = require('node-sass-middleware');
require('dotenv').config();
const app = express();
const router = require('./api/router');
const port = process.env.PORT || 3000;
const db_uri = process.env.MONGODB_URI;
mongoose.connect(db_uri, { useNewUrlParser: true });
const db = mongoose.connection;
db.on('error', error => console.log(error));
db.once('open', () => console.log('MongoDB connection established'));
const loggerTool = (req, res, next) => {
const now = new Date().toLocaleString();
const log = `${now}: ${req.method} ${req.url}`;
console.log(log);
fs.appendFile('server.log', log + '\n', err => {
if (err) console.log('Unable to append to file');
});
next();
};
const publicDir = path.resolve('public');
// Set view-engine
app.set('view engine', 'pug');
app.use(
sassMiddleware({
src: publicDir,
dest: publicDir,
indentedSyntax: false, // true = .sass and false = .scss
sourceMap: true,
}),
);
// Config server
app
.use(cors())
.use(express.json())
.use(express.static(publicDir))
.use(express.urlencoded({extended:false}))
.use(loggerTool)
.use(router);
// Error handling
app.use((req, res, next) => {
const error = new Error('Not found');
error.status = 404;
next(error);
})
app.use((error, req, res, next) => {
res.status(error.status || 500).json({
message: error.message
});
})
app.listen(port, () => console.log(`Server is running on port: ${port}`));