UNPKG

3.97 kBJavaScriptView Raw
1/**
2 * Module Dependencies
3 *
4 * @ignore
5 */
6var bodyParser = require('body-parser')
7var contentLength = require('express-content-length-validator')
8var Dispatcher = require('structure-dispatcher').default
9var express = require('express')
10var helmet = require('helmet')
11var hpp = require('hpp')
12var logger = require('structure-logger')
13var path = require('path')
14var Router = require('structure-router')
15var serveStatic = require('serve-static')
16var WebsocketServer = require('structure-websocket-server')
17
18function removePoweredBy(req, res, next) {
19 res.removeHeader('X-Powered-By')
20 next()
21}
22
23/**
24 * Server Class
25 *
26 * @public
27 * @class Server
28 */
29class Server {
30
31 /**
32 * Server constructor
33 *
34 * @public
35 * @constructor
36 * @param {Object} options - Options
37 */
38 constructor(options = {}) {
39
40 var defaults = {
41 cursors: options.cursors || [],
42 db: true,
43 drain: true,
44 sockets: true
45 }
46
47 this.options = Object.assign({}, defaults, options)
48
49 this.server = express()
50
51 /*if(process.env.NODE_ENV != 'test') {
52 this.server.use(require('express-status-monitor')())
53 }*/
54 this.server.use(serveStatic(path.join(__dirname, '../public')))
55 this.server.use(bodyParser.urlencoded({extended: true}))
56 this.server.use(bodyParser.json({strict: false}))
57 //this.server.use(removePoweredBy)
58 this.server.use(helmet())
59 this.server.use(hpp())
60 this.server.use(contentLength.validateMax({max: process.env.MAX_CONTENT_LENGTH, status: 400, message: 'stop it!'}))
61
62 if(process.env.NODE_ENV != 'test') {
63 this.server.use(this.logRequestInfo)
64 }
65
66 this.router = options.router || new Router({
67 dispatcher: options.dispatcher || new Dispatcher(),
68 routes: options.routes
69 })
70
71 /*if(process.env.LOG_LEVEL == 'debug') {
72 logger.debug('Routes list:')
73 this.debugRoutes()
74 }*/
75
76 }
77
78 closeCursors() {
79 var cursors = require('./cursors')
80
81 for(let i = 0, l = cursors.length; i < l; i++) {
82 var cursor = cursors[i]
83 cursor.close()
84 }
85
86 cursors = []
87
88 }
89
90 /**
91 * List of routes registered with Express including middleware routes
92 *
93 * @private
94 */
95 debugRoutes() {
96 var route, routes = []
97
98 this.server._router.stack.forEach(function(middleware) {
99 if(middleware.route) {
100 routes.push(middleware.route)
101 } else if(middleware.name === 'router') { // router middleware
102 middleware.handle.stack.forEach(function(handler) {
103 route = handler.route
104 route && routes.push(route)
105 })
106 }
107 })
108
109 routes.forEach( (route) => {
110
111 var method = Object.keys(route.methods)[0].toUpperCase()
112
113 console.error(`${method} ${route.path}`)
114
115 })
116
117 }
118
119 /**
120 * Log each HTTP request's method and url
121 *
122 * @private
123 * @param {Object} req - Express req
124 * @param {Object} res - Express res
125 * @param {Function} next - Express next
126 */
127 logRequestInfo(req, res, next) {
128
129 logger.info(req.method, req.originalUrl)
130 next()
131
132 }
133
134 /**
135 * Start the HTTP Server
136 *
137 * @public
138 */
139 start() {
140
141 this.router.start(this.server)
142
143 this.server = this.server.listen(this.options.port || process.env.EXPRESS_PORT)
144
145 if(this.options.sockets) {
146 this.wss = new WebsocketServer(this.server)
147 }
148
149 if(this.options.db) {
150 this.cursors = []
151 }
152
153 logger.debug('Structure API started at:', `http://localhost:${process.env.EXPRESS_PORT}`)
154
155 }
156
157 /**
158 * Stop the HTTP Server
159 *
160 * @public
161 */
162 stop() {
163
164 if(this.options.db) {
165 var r = require('../lib/database/driver')
166 if(this.options.drain) r.getPoolMaster().drain()
167 this.closeCursors()
168 }
169
170 if(this.options.sockets) {
171 this.wss.stop()
172 }
173
174 this.server.close()
175
176 }
177
178 /**
179 * Add Express middleware to the Express server object
180 *
181 * @public
182 */
183 use() {
184
185 this.server.use.apply(this.server, arguments)
186
187 }
188
189}
190
191module.exports = Server