/
index.js
222 lines (198 loc) · 5.89 KB
/
index.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
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
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
/*
* @Author: Mike Reich
* @Date: 2015-07-16 10:52:58
* @Last Modified 2016-02-20
*/
/**
* [![Build Status](https://travis-ci.org/nxus/router.svg?branch=master)](https://travis-ci.org/nxus/router)
*
* The Nxus router is an Express compatible web server and router for Nxus applications.
*
* ## Installation
*
* In your Nxus application:
*
* > npm install @nxus/router --save
*
* ## Usage
*
* ### Defining a route
*
* app.get('router').route('/', (req, res) => {
* res.send('Hello World')
* })
*
* Alternatively, you can specify a HTTP method:
*
* app.get('router').route('GET', '/', (req, res) => {
* res.send('Hello World')
* })
*
* ### Adding Express/connect middleware
*
* app.get('router').middleware((req, res) => {
* res.status(404).send('Nothing to see here');
* })
*
* ### Adding static files/directories
*
* app.get('router').static("my-prefix", myPath)
*
* For example, `myFile.txt` in `myPath` is then available at the url `/my-prefix/myFile.txt`
*
* Sometimes its good to have a static assets folder where all your assets live. For that reason, you can use the `assets` gatherer.
*
* # API
* -----
*/
'use strict';
require('babel-runtime/core-js/promise').default = require('bluebird');
var util = require('util')
var express = require('express');
var _ = require('underscore');
var bodyParser = require('body-parser');
var flash = require('connect-flash');
var compression = require('compression');
/**
* @class Router provides Express based HTTP routing
*/
class Router {
/**
* Sets up the relevant gather/providers
* @param {Nxus Application} app the App
*/
constructor (app) {
this.app = app
this.port = app.config.PORT || 3001
this.middleware = []
this.routeTable = []
this.registered = false
app.get('router').use(this)
.gather('middleware', this.setMiddleware.bind(this))
.gather('static', this.setStatic.bind(this))
.gather('route', this.setRoute.bind(this))
.respond('getRoutes')
.respond('getExpressApp')
.respond('setStatic')
.respond('setRoute')
.respond('setRoute.get', (route, handler) => {
this.setRoute('GET', route, handler);
})
.respond('setRoute.post', (route, handler) => {
this.setRoute('POST', route, handler);
});
this._setup()
app.once('launch.before', this._registerRoutes.bind(this));
app.once('launch', this.launch.bind(this))
app.once('stop', this.stop.bind(this))
}
_setup() {
this._setupExpress()
this.app.once('startup', () => {
this.expressApp.use((err, req, res, next) => {
if (this.app.config.NODE_ENV != "production") return next()
app.log.error(
'HTTP 500 error serving request\n\n',
"Error:\n\n" + err.toString ? err.toString() : "N/A",
"Error Stack:\n\n" + err.stack ? err.stack : "N/A",
"User:\n\n" + util.inspect(req.user, {depth: 3}),
"\n\n\nRequest:\n\n" + util.inspect(req, {depth: 1}),
err
)
res.status(500)
res.redirect('/error')
})
})
}
_setupExpress() {
this.expressApp = express()
//Setup express app
this.expressApp.use(compression())
this.expressApp.use(flash())
this.expressApp.use(bodyParser.urlencoded({ extended: false }));
this.expressApp.use(bodyParser.json());
this.expressApp.use((req, res, next) => {
res.set('Connection', 'close'); //need to turn this off on production environments
next();
})
}
/**
* Launches the Express app. Called by the app.load event.
*/
launch() {
this.app.log('Starting app on port:', this.port);
this.server = this.expressApp.listen(this.port);
}
/**
* Stops the express app. Called by the app.stop event.
*/
stop() {
if (this.server) {
this.app.log('Shutting down app on port:', this.port);
this.server.close();
}
}
/**
* Returns the internal routing table.
* @return {array} routes which have been registered
*/
getRoutes() {
return this.routeTable;
}
/**
* Returns the Express App instance.
* @return {Instance} ExpressJs app instance.
*/
getExpressApp() {
return this.expressApp;
}
/**
* Adds a middleware handler to the internal routing table passed to Express. Accessed with 'middleware' gather.
* @param {string} route A URL route.
* @param {function} handler An ExpressJs type callback to handle the route.
*/
setMiddleware (route, handler, method='use') {
this._registerRoute({method, route, handler})
}
/**
* Adds a route to the internal routing table passed to Express. Accessed with the 'route' gather.
* @param {string} method Either 'get', 'post', 'put' or 'delete'.
* @param {string} route A URL route.
* @param {function} handler An ExpressJs type callback to handle the route.
*/
setRoute (method, route, handler) {
if(!handler) {
handler = route
route = method
method = 'use'
}
method = method.toLowerCase();
this.routeTable.push({method, route, handler})
if(this.registered) this._registerRoute({method, route, handler})
}
/**
* Adds a path to serve static files.
* @param {string} prefix The path at which the static files will be accessible. For example: /js
* @param {string} path A fully resolved path.
*/
setStatic (prefix, path) {
this.app.log.debug('setting-static', prefix)
this.expressApp.use(prefix, express.static(path))
}
_registerRoutes () {
this.registered = true
this.routeTable.reverse().forEach((r) => {
this._registerRoute(r)
})
}
_registerRoute(r) {
if(_.isString(r.route)) {
this.app.log.debug('Registering route', r.method, r.route)
this.expressApp[r.method](r.route, r.handler);
} else {
this.app.log.debug('Registering middleware')
this.expressApp[r.method](r.route);
}
}
}
export default Router