This repository has been archived by the owner on Feb 1, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 8
/
server.ts
194 lines (158 loc) · 5.01 KB
/
server.ts
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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
'use strict';
// Can't use import here yet since harmony-modules
// Check out node --v8-options | grep harmony
import * as express from 'express';
const bodyParser = require('body-parser');
const helmet = require('helmet');
const morgan = require('morgan'); // HTTP request Logger middleware for node.js
const winston = require('winston'); // Logger
const localization = require('i18n');
const path = require('path');
const nunjucks = require('nunjucks');
const cookieParser = require('cookie-parser');
const favicon = require('serve-favicon');
const nconf = require('nconf');
// Setup nconf to use (in-order):
// 1. Command-line arguments
// 2. Environment variables
// 3. A file located at './config.json'
nconf.argv().env().file({ file: './config.json' });
nconf.defaults({
'NODE_ENV': 'development',
'NODE_PATH': '.',
'PORT': 3000,
// custom flags
'appName': 'NodeExample',
'logLevel': 'warn',
'logInJson': false,
'lang': 'en-US'
});
// Environment variables
const ROOT: string = nconf.get('NODE_PATH');
const ENV: string = nconf.get('NODE_ENV');
const PORT: string = nconf.get('PORT');
// Helper variables
const isDev: Boolean = ENV === 'development';
const lang: string = nconf.get('lang');
const srcPath: string = `${ROOT}/src/`;
const views: string = path.join(srcPath, 'views');
// Utils Import
import {Logger, LoggerMiddleware, Debug} from './src/utils';
import * as CustomInterfaces from './src/utils/interfaces';
// Set debug function
const debug: Function = Debug('server');
debug('isDev', isDev);
debug('srcPath', srcPath);
debug('Views path', views);
// Express
const app: express.Express = express();
// view engine setup
app.engine('njk', nunjucks.render);
app.set('views', views);
app.set('view engine', 'njk');
const env = nunjucks.configure(views, {
autoescape: true,
watch: isDev,
noCache: isDev,
express: app,
});
// Configure localization
localization.configure({
locales: ['en-US', 'es'],
defaultLocale: 'en-US',
cookie: 'lang',
queryParameter: 'lang',
directory: `${ROOT}/src/locales`,
autoReload: isDev,
api: {
'__': 't', // now req.__ becomes req.t
'__n': 'tn' // and req.__n can be called as req.tn
}
});
// Setup Middlewares
app.use(helmet());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(cookieParser());
app.use(localization.init); // i18n init parses req for language headers, cookies, etc.
app.use(favicon(path.join(srcPath, 'public', 'favicon.ico')));
app.use(express.static(path.join(srcPath, 'public')));
if (isDev) {
app.use(morgan('dev'));
}
// Pass translation function to templates
app.use((req: CustomInterfaces.CustomRequest, res: CustomInterfaces.CustomResponse, next: Function) : void => {
debug('Passing translation functions to templates');
env.addGlobal('translate', req.t);
env.addGlobal('pluralTranslate', req.tn);
next();
});
// Add the logger middleware so we can capture data automatically
app.use(LoggerMiddleware(Logger));
// Routes
app.use(require('./src/routes'));
// catch 404 and forward to error handler
app.use((req: CustomInterfaces.CustomRequest, res: CustomInterfaces.CustomResponse) : void => {
Logger.info('404 page not found');
let err : CustomInterfaces.Error = new Error('Not Found');
let data: CustomInterfaces.DevMessage = {
dev_message: err.message,
stack: err.stack,
show: isDev,
};
let status: number = 404;
res.status(status);
res.render('errors/404', data);
debug('%s params %s', status, JSON.stringify(data));
});
// development error handler
// will print stacktrace
app.use((err: CustomInterfaces.Error, req: CustomInterfaces.CustomRequest,
res: CustomInterfaces.CustomResponse) : void => {
let data: CustomInterfaces.DevMessage = {
dev_message: err.message ? err.message : 'No Message',
stack: err.stack,
show: isDev,
};
let status: number = err.status || 500;
res.status(status);
Logger.error(err.stack);
res.render('errors/error', data);
debug('%s params %s', status, JSON.stringify(data));
});
// Start up the server
app.listen(PORT, (err?: any) : void => {
if (err) {
Logger.error(err);
return;
}
Logger.info('Environment:', ENV);
Logger.info(`Listening on port ${PORT}`);
debug('Environment:', ENV);
debug(`Listening on port ${PORT}`);
});
process.on('error', (error: NodeJS.ErrnoException) => {
if (error.syscall !== 'listen') {
throw error;
}
let bind : string = typeof PORT === 'string' ? `Pipe ${PORT}` : `Port ${PORT}`;
// handle specific listen errors with friendly messages
switch (error.code) {
case 'EACCES':
Logger.error(bind + ' requires elevated privileges');
process.exit(1);
break;
case 'EADDRINUSE':
Logger.error(bind + ' is already in use');
process.exit(1);
break;
default:
throw error;
}
});
// Process uncaught exception
process.on('uncaughtException', function(err: CustomInterfaces.Error) {
Logger.error((new Date).toUTCString() + ' uncaughtException:', err.message);
Logger.error(err.stack);
});
module.exports = app;