-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserver.js
415 lines (389 loc) · 12.3 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
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
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
'use strict'
let args = process.argv.slice(2),
express = require('express'),
fs = require('fs-extra'),
walker = require('klaw-sync'),
am = require('async-methods'),
join = require('path').join,
bodyParser = require('body-parser'),
platform = require('os').platform(),
shell = require('shelljs'),
cookieParser = require('cookie-parser'),
axios = require('axios'),
defaultConfig = {
port: 8081,
auto: false,
defaults: {
response_status: 200,
method: 'GET',
attachment: false,
filename: '',
type: '',
CORS: true
},
public: 'public',
apis: []
}
class ApiResponder {
constructor(config, port, app, staticFolder) {
let self = this
this.config =
typeof config === 'string'
? require(join(__dirname, config))
: typeof config === 'object' ? config : defaultConfig
this.config.defaults = this.config.defaults || {}
for (var attr in defaultConfig.defaults) {
if (this.config.defaults[attr] === undefined) {
this.config.defaults[attr] = defaultConfig.defaults[attr]
}
}
self.setPort(port)
if (staticFolder) {
this.config.public = staticFolder
}
self.autoConfigureRoutes()
// start server or route only
let apiResponder = am(function(cb) {
if (!app) {
self.initServer(cb)
} else {
self.app = app
self.initRouter(cb)
}
})
this.then = fn => apiResponder.then(fn)
this.catch = fn => apiResponder.catch(fn)
return self
}
initServer(cb) {
let self = this,
app = (self.app = express())
self.server = require('http').Server(self.app)
var lsof,
port = self.port,
listen = function() {
// allow posts up to 50MB in size
app.use(
bodyParser.json({
limit: '50mb'
})
)
app.use(
bodyParser.urlencoded({
limit: '50mb',
extended: true
})
)
// provides req.cookies
app.use(cookieParser())
// serve everything in 'public' folder as static files
let staticFolder = (typeof self.config === 'object' && self.config.public) || 'public'
app.use(express.static(staticFolder))
self.server.listen(port, '0.0.0.0', function() {
console.log(' [router] Responder listening on port ' + port)
console.log(' [router] Static files in ' + join(__dirname, staticFolder))
console.log()
self.initRouter(cb)
console.log()
})
}
// check if port alreay in use
// don't check in hosted environment or Windows
if (!process.env.PORT && !process.env.port && (platform === 'darwin' || platform === 'linux')) {
lsof = shell.exec('lsof -i :' + port, function(id, output) {
// if a 'node' process is already using requested port, kill process
if (output.split('\n').length > 1) {
var listening = false
output.split('\n').forEach(function(line) {
if (!listening && line && line.substr(0, 4) === 'node') {
listening = true
var pid = line.replace(/\s+/g, '|').split('|')[1]
shell.exec('kill -9 ' + pid, function() {
console.log('[router] Killing process ' + pid + ' already usng port ' + port)
listen()
})
}
})
if (!listening) {
listen()
}
} else {
listen()
}
})
} else {
listen()
}
}
initRouter(cb) {
let self = this,
config = this.config,
app = this.app
if (!config.apis.length) {
console.log('[router] No endpoints defined yet')
}
// add a route for each api response in config
config.apis.forEach(function(endpointConfig, index) {
console.log(
' ' +
(index + 1) +
'. ' +
(endpointConfig.method || config.defaults.method) +
' ' +
endpointConfig.endpoint
)
var method = (endpointConfig.method || config.defaults.method).toLowerCase()
if (endpointConfig.middleware) {
app[method](endpointConfig.endpoint, endpointConfig.middleware, function(req, res) {
self.responder(endpointConfig, req, res)
})
} else {
app[method](endpointConfig.endpoint, function(req, res) {
// pass route to responder
self.responder(endpointConfig, req, res)
})
}
})
cb(null, {
server: self.server,
app: self.app,
config: self.config,
addPublic: self.addPublic
})
}
rproxy(api) {
if (typeof api.transformRequest === 'function') {
api.transformRequest(api)
}
let config =
typeof api.rproxy === 'function'
? api.rproxy(api)
: typeof api.rproxy === 'string' ? { url: api.rproxy } : api.rproxy
config.headers = config.headers || {}
config.params = config.params || {}
config.method = config.method || api.req.method
for (var attr in api.req.headers) {
if (attr !== 'host' && attr !== '') {
config.headers[attr] = api.req.headers[attr]
}
}
for (var attr in api.req.query) {
config.params[attr] = api.req.query[attr]
}
if (api.body) {
config.data = api.body
}
return am(axios(config))
.next(response => {
api.response_status = response.status
if (api.transformResponse) {
if (am.isGenerator(api.transformResponse)) {
return am(api.transformResponse, response.data)
} else {
return api.transformResponse(response.data)
}
} else {
return response.data
}
})
.error(err => {
api.res.statusMessage = err.response.statusText
api.res.response_status = err.response.statusText
return err.response.data
})
}
responder(endpointConfig, req, res) {
var api,
argsHaveClass,
classArgs = [],
self = this,
timer = new Date().getTime(),
api = { req: req, res: res }
if (endpointConfig.methodName) {
classArgs = [endpointConfig.methodName]
}
classArgs.push(endpointConfig.responder)
argsHaveClass = am.argumentsHaveClass(classArgs)
for (var attr in self.config.defaults) {
api[attr] = self.config.defaults[attr]
}
// endpoint routes can overide default
for (attr in endpointConfig) {
api[attr] = endpointConfig[attr]
}
;['query', 'body', 'params', 'cookies', 'headers', 'url'].forEach(attr => {
api[attr] = req[attr]
})
am(
new Promise(function(resolve, reject) {
try {
if (api.rproxy) {
self
.rproxy(api)
.then(resolve)
.catch(reject)
} else if (argsHaveClass) {
if (argsHaveClass.methodName && argsHaveClass.classFn) {
am.ExtendedPromise._applyResultToClass
.apply(api, [argsHaveClass])
.then(result => {
resolve(result)
})
.catch(reject)
} else {
am.ExtendedPromise._applyResultToClass(argsHaveClass, [api])
.then(resolve)
.catch(reject)
}
} else if (am.isGenerator(api.responder)) {
am(api.responder.apply(api))
.then(resolve)
.catch(reject)
} else {
api.responder.apply(this, [api, resolve, reject])
}
} catch (e) {
reject(e)
}
})
)
.next(response => {
if (response !== undefined) {
api.response = response
}
timer = new Date().getTime() - timer
// send the response
if (api.CORS) {
res.header('Access-Control-Allow-Origin', '*')
res.header(
'Access-Control-Allow-Headers',
'Origin, X-Requested-With, Content-Type, Accept'
)
}
// if response is a file the api-config should set api.type and api.filepath
// corresponding to requested file
if (api.filepath) {
if (!api.type && api.filepath.lastIndexOf('.') !== -1) {
api.type = api.filepath.substr(api.filepath.lastIndexOf('.') + 1)
}
fs.readFile(api.filepath, function(err, file) {
// sets mime-type
res.type(api.type)
if (api.attachment) {
// sets content disposition and mime-type
// eg Content-Disposition: attachment filename="xxx.pdf"
res.attachment(api.filepath)
}
res.status(api.response_status).send(file)
})
return
}
// send the response
if (typeof api.response === 'object') {
res.type(api.type || 'application/json')
} else if (api.type) {
res.type(api.type)
}
res.status(api.response_status).send(api.response)
})
.error(err => {
res.status(500).send(err)
})
}
addPublic(path) {
if (typeof path === 'string') {
this.app.use(express.static(path))
}
}
setPort(port) {
port = port || null
this.config.port = this.port =
process.env.PORT || process.env.port || port || this.config.port || 8081
}
autoConfigureRoutes() {
if (!this.config || !this.config.auto || !this.config.apis) {
return
}
let self = this,
endpointsDirectory = join(__dirname, self.config.auto),
endpointFiles = []
am(fs.access(endpointsDirectory))
.then(() => {
endpointFiles = walker(endpointsDirectory, {
nodir: true,
filter: file => {
return file.path.indexOf('.js') !== -1
}
})
let treeBasedRoutes = endpointFiles.map(file => {
let endpoint = { method: 'get' }
if (file.path.indexOf('post.js') !== -1) {
endpoint.method = 'post'
endpoint.endpoint = file.path.replace(endpointsDirectory, '').replace(/post\.js/i, '')
} else if (file.path.indexOf('put.js') !== -1) {
endpoint.method = 'post'
endpoint.endpoint = file.path.replace(endpointsDirectory, '').replace(/post\.js/i, '')
} else if (file.path.indexOf('head.js') !== -1) {
endpoint.method = 'post'
endpoint.endpoint = file.path.replace(endpointsDirectory, '').replace(/post\.js/i, '')
} else {
endpoint.endpoint = file.path.replace(endpointsDirectory, '').replace(/\.js/i, '')
}
endpoint.responder = require(file.path)
self.config.apis.push(endpoint)
})
})
.catch(err => {
console.log('Nominated auto directory, ', defaultConfig.auto, "doesn't exist")
})
}
static parseArgsAndInit(args) {
let port, app, config, staticFolder
try {
args.forEach((arg, i) => {
if ((arg.indexOf('-config') === 0 || arg.indexOf('--config') === 0) && args[i + 1]) {
config = args[i + 1]
}
if ((arg.indexOf('-port') === 0 || arg.indexOf('--port') === 0) && args[i + 1]) {
port = args[i + 1]
}
if ((arg.indexOf('-public') === 0 || arg.indexOf('--public') === 0) && args[i + 1]) {
staticFolder = args[i + 1]
}
})
} catch (e) {}
let apiResponder = new ApiResponder(config, port, app, staticFolder)
}
}
// when invoked with node server -port xxx -config xxx -public xxx
// // when invoked via require - define module.exports
if (require.main === module) {
ApiResponder.parseArgsAndInit(args)
} else {
exports = function(config, port, app) {
let apiResponder
for (var i = 0; i < arguments.length; i++) {
if (
arguments[i].constructor &&
arguments[i].constructor.name &&
arguments[i].constructor.name === 'EventEmitter'
) {
// app passed
app = arguments[i]
}
if (typeof arguments[i] === 'object' || typeof arguments[i] === 'string') {
config = arguments[i]
} else if (typeof arguments[i] === 'number') {
// app passed
port = arguments[i]
}
}
apiResponder = new ApiResponder(config, port, app)
exports.app = apiResponder.app
if (apiResponder.server) {
exports.server = apiResponder.server
}
return apiResponder
}
module.exports = exports
}