-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
93 lines (92 loc) · 2.55 KB
/
app.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
// environment
const env = process.env.NODE_ENV || 'development';
// express
const express = require('express');
const app = express();
// socket
const server = require('http').Server(app);
const io = require('socket.io')(server);
// body parser
const bodyParser = require('body-parser');
app.use(bodyParser.json());
// mongoose
const mongoose = require('mongoose');
const config = require('./config/database');
// connect to mongoose
mongoose.connect(config.database, {
useMongoClient: true
});
var db = mongoose.connection;
// db connected
db.on('connected', () => {
console.log('Connected to database: ' + config.database);
});
// db error
db.on('error', (err) => {
console.log('Database error: ' + err);
});
// API TEST
const endpoint = '/api';
app.get('/', (req, res) => res.send('Please use /api as endpoint.'));
app.get(endpoint, (req, res) => res.send('API is working.'));
// morgan logger
const morgan = require('morgan');
const fs = require('fs');
const path = require('path');
const rfs = require('rotating-file-stream');
const logDirectory = path.join(__dirname, 'log');
// ensure log directory exists
fs.existsSync(logDirectory) || fs.mkdirSync(logDirectory);
// create a rotating write stream
const accessLogStream = rfs('access.log', {
interval: '1d', // rotate daily
compress: 'gzip', // compress rotated files
path: logDirectory
});
// setup the logger
app.use(morgan('combined', {stream: accessLogStream}));
// cors
const cors = require('cors');
app.use(cors());
// winston logger
const winston = require('winston');
const tsFormat = () => (new Date()).toLocaleTimeString();
const logger = new (winston.Logger)({
transports: [
// colorize the output to the console
new (winston.transports.Console)({
timestamp: tsFormat,
colorize: true,
level: 'info'
}),
new (require('winston-daily-rotate-file'))({
filename: `${logDirectory}/-results.log`,
timestamp: tsFormat,
datePattern: 'yyyy-MM-dd',
prepend: true,
level: env === 'development' ? 'verbose' : 'info'
})
]
});
// ROUTES
// tasklist
var tasklist = require('./routes/tasklist');
app.use(endpoint + '/tasklist', tasklist);
// SOCKETS
// tasklist
require('./socket/tasklist')(io);
// error handling
app.use(logErrors);
app.use(errorHandler);
// console error
function logErrors (err, req, res, next) {
logger.error(err);
console.error(err);
next(err);
}
// response loggin error
function errorHandler (err, req, res, next) {
res.status(500).send({error: err});
}
// listen
server.listen(config.port, () => console.log('Connected on port ' + config.port));