forked from jeremydaly/lambda-api
-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
495 lines (370 loc) · 14.2 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
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
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
'use strict'
/**
* Lightweight web framework for your serverless applications
* @author Jeremy Daly <[email protected]>
* @version 0.10.1
* @license MIT
*/
const REQUEST = require('./lib/request') // Resquest object
const RESPONSE = require('./lib/response') // Response object
const UTILS = require('./lib/utils') // Require utils library
const LOGGER = require('./lib/logger') // Require logger library
const prettyPrint = require('./lib/prettyPrint') // Pretty print for debugging
const { ConfigurationError } = require('./lib/errors') // Require custom errors
// Create the API class
module.exports = class LambdaAPI {
// Create the constructor function.
constructor(props) {
// Set the version and base paths
this._version = props && props.version ? props.version : 'v1'
this._base = props && props.base && typeof props.base === 'string' ? props.base.trim() : ''
this._callbackName = props && props.callback ? props.callback.trim() : 'callback'
this._mimeTypes = props && props.mimeTypes && typeof props.mimeTypes === 'object' ? props.mimeTypes : {}
this._serializer = props && props.serializer && typeof props.serializer === 'function' ? props.serializer : JSON.stringify
// Set sampling info
this._sampleCounts = {}
// Init request counter
this._requestCount = 0
// Track init date/time
this._initTime = Date.now()
// Logging levels
this._logLevels = {
trace: 10,
debug: 20,
info: 30,
warn: 40,
error: 50,
fatal: 60
}
// Configure logger
this._logger = LOGGER.config(props && props.logger,this._logLevels)
// Prefix stack w/ base
this._prefix = this.parseRoute(this._base)
// Stores route mappings
this._routes = {}
// Init callback
this._cb
// Error middleware stack
this._errors = []
// Store app packages and namespaces
this._app = {}
// Executed after the callback
this._finally = () => {}
// Global error status (used for response parsing errors)
this._errorStatus = 500
// Methods
this._methods = ['get','post','put','patch','delete','options','head','any']
// Convenience methods for METHOD
this._methods.forEach(m => {
this[m] = (...a) => this.METHOD(m.toUpperCase(),...a)
})
} // end constructor
// METHOD: Adds method, middleware, and handlers to routes
METHOD(method,...args) {
// Extract path if provided, otherwise default to global wildcard
let path = typeof args[0] === 'string' ? args.shift() : '/*'
// Extract the execution stack
let stack = args.map((fn,i) => {
if (typeof fn === 'function' && (fn.length === 3 || (i === args.length-1)))
return fn
throw new ConfigurationError('Route-based middleware must have 3 parameters')
})
if (stack.length === 0)
throw new ConfigurationError(`No handler or middleware specified for ${method} method on ${path} route.`)
// Ensure method is an array
let methods = Array.isArray(method) ? method : method.split(',')
// Parse the path
let parsedPath = this.parseRoute(path)
// Split the route and clean it up
let route = this._prefix.concat(parsedPath)
// For root path support
if (route.length === 0) { route.push('') }
// Keep track of path variables
let pathVars = {}
// Make a local copy of routes
let routes = this._routes
// Create a local stack for inheritance
let _stack = {}
// Loop through the paths
for (let i=0; i<route.length; i++) {
let end = i === route.length-1
// If this is a variable
if (/^:(.*)$/.test(route[i])) {
// Assign it to the pathVars (trim off the : at the beginning)
pathVars[i] = [route[i].substr(1)]
// Set the route to __VAR__
route[i] = '__VAR__'
} // end if variable
// Add methods to routess
methods.forEach(_method => {
if (typeof _method === 'string') {
if (routes['ROUTES']) {
// Wildcard routes
if (routes['ROUTES']['*']) {
// Inherit middleware
if (routes['ROUTES']['*']['MIDDLEWARE']) {
_stack[method] = routes['ROUTES']['*']['MIDDLEWARE'].stack
//_stack[method] ?
// _stack[method].concat(routes['ROUTES']['*']['MIDDLEWARE'].stack)
// : routes['ROUTES']['*']['MIDDLEWARE'].stack
}
// Inherit methods and ANY
if (routes['ROUTES']['*']['METHODS'] && routes['ROUTES']['*']['METHODS']) {
['ANY',method].forEach(m => {
if (routes['ROUTES']['*']['METHODS'][m]) {
_stack[method] = _stack[method] ?
_stack[method].concat(routes['ROUTES']['*']['METHODS'][m].stack)
: routes['ROUTES']['*']['METHODS'][m].stack
}
}) // end for
}
}
// Matching routes
if (routes['ROUTES'][route[i]]) {
// Inherit middleware
if (end && routes['ROUTES'][route[i]]['MIDDLEWARE']) {
_stack[method] = _stack[method] ?
_stack[method].concat(routes['ROUTES'][route[i]]['MIDDLEWARE'].stack)
: routes['ROUTES'][route[i]]['MIDDLEWARE'].stack
}
// Inherit ANY methods (DISABLED)
// if (end && routes['ROUTES'][route[i]]['METHODS'] && routes['ROUTES'][route[i]]['METHODS']['ANY']) {
// _stack[method] = _stack[method] ?
// _stack[method].concat(routes['ROUTES'][route[i]]['METHODS']['ANY'].stack)
// : routes['ROUTES'][route[i]]['METHODS']['ANY'].stack
// }
}
}
// Add the route to the global _routes
this.setRoute(
this._routes,
_method.trim().toUpperCase(),
(end ? {
vars: pathVars,
stack,
inherited: _stack[method] ? _stack[method] : [],
route: '/'+parsedPath.join('/'),
path: '/'+this._prefix.concat(parsedPath).join('/')
} : null),
route.slice(0,i+1)
)
}
}) // end methods loop
routes = routes['ROUTES'][route[i]]
} // end for loop
} // end main METHOD function
// RUN: This runs the routes
async run(event,context,cb) {
// Set the event, context and callback
this._event = event || {}
this._context = this.context = typeof context === 'object' ? context : {}
this._cb = cb ? cb : undefined
// Initalize request and response objects
let request = new REQUEST(this)
let response = new RESPONSE(this,request)
try {
// Parse the request
await request.parseRequest()
// Loop through the execution stack
for (const fn of request._stack) {
// Only run if in processing state
if (response._state !== 'processing') break
await new Promise(async r => {
try {
let rtn = await fn(request,response,() => { r() })
if (rtn) response.send(rtn)
if (response._state === 'done') r() // if state is done, resolve promise
} catch(e) {
await this.catchErrors(e,response)
r() // resolve the promise
}
})
} // end for
} catch(e) {
await this.catchErrors(e,response)
}
// Added: await for finally //
await this._finally(request, response)
// Return the final response
return response._response
} // end run function
// Catch all async/sync errors
async catchErrors(e,response,code,detail) {
// Error messages should never be base64 encoded
response._isBase64 = false
// Strip the headers (TODO: find a better way to handle this)
response._headers = {}
let message
// Set the status code
response.status(code ? code : this._errorStatus)
let info = {
detail,
statusCode: response._statusCode,
coldStart: response._request.coldStart,
stack: this._logger.stack && e.stack || undefined
}
if (e instanceof Error) {
message = e.message
this.log.fatal(message,info)
} else {
message = e
this.log.error(message,info)
}
// If first time through, process error middleware
if (response._state === 'processing') {
// Flag error state (this will avoid infinite error loops)
response._state = 'error'
// Execute error middleware
for (const err of this._errors) {
if (response._state === 'done') break
// Promisify error middleware
await new Promise(r => {
let rtn = err(e,response._request,response,() => { r() })
if (rtn) response.send(rtn)
})
} // end for
}
// Throw standard error unless callback has already been executed
if (response._state !== 'done') response.json({'error':message})
} // end catch
// Custom callback
async _callback(err,res,response) {
// Set done status
response._state = 'done'
// Execute finally
// await this._finally(response._request,response)
// Output logs
response._request._logs.forEach(log => {
console.log(JSON.stringify(this._logger.detail ? // eslint-disable-line no-console
this._logger.format(log,response._request,response) : log))
})
// Generate access log
if ((this._logger.access || response._request._logs.length > 0) && this._logger.access !== 'never') {
let access = Object.assign(
this._logger.log('access',undefined,response._request,response._request.context),
{ statusCode: res.statusCode, coldStart: response._request.coldStart, count: response._request.requestCount }
)
console.log(JSON.stringify(this._logger.format(access,response._request,response))) // eslint-disable-line no-console
}
// Reset global error code
this._errorStatus = 500
// Execute the primary callback
typeof this._cb === 'function' && this._cb(err,res)
} // end _callback
// Middleware handler
use(...args) {
// Extract routes
let routes = typeof args[0] === 'string' ? Array.of(args.shift()) : (Array.isArray(args[0]) ? args.shift() : ['/*'])
// Init middleware stack
let middleware = []
// Add func args as middleware
for (let arg in args) {
if (typeof args[arg] === 'function') {
if (args[arg].length === 3) {
middleware.push(args[arg])
} else if (args[arg].length === 4) {
this._errors.push(args[arg])
} else {
throw new ConfigurationError('Middleware must have 3 or 4 parameters')
}
}
}
// Add middleware to path
if (middleware.length > 0) {
routes.forEach(route => {
this.METHOD('__MW__',route,...middleware)
})
}
} // end use
// Finally handler
finally(fn) {
this._finally = fn
}
//-------------------------------------------------------------------------//
// UTILITY FUNCTIONS
//-------------------------------------------------------------------------//
parseRoute(path) {
return path.trim().replace(/^\/(.*?)(\/)*$/,'$1').split('/').filter(x => x.trim() !== '')
}
// Recursive function to create/merge routes object
setRoute(obj, method, value, path) {
if (path.length > 1) {
let p = path.shift()
if (p === '*') { throw new ConfigurationError('Wildcards can only be at the end of a route definition') }
this.setRoute(obj['ROUTES'][p], method, value, path)
} else {
// Create routes and add path if they don't exist
if (!obj['ROUTES']) obj['ROUTES'] = {}
if (!obj['ROUTES'][path[0]]) obj['ROUTES'][path[0]] = {}
// If a value exists in this iteration
if (value !== null) {
// If mounting middleware
if (method === '__MW__') {
// Merge stacks if middleware exists
if (obj['ROUTES'][path[0]]['MIDDLEWARE']) {
value.stack = obj['ROUTES'][path[0]]['MIDDLEWARE'].stack.concat(value.stack)
value.vars = UTILS.mergeObjects(obj['ROUTES'][path[0]]['MIDDLEWARE'].vars,value.vars)
}
// Add/Update the middleware
obj['ROUTES'][path[0]]['MIDDLEWARE'] = value
// Else if mounting a regular route
} else {
// Create the methods section if it doesn't exist
if (!obj['ROUTES'][path[0]]['METHODS']) obj['ROUTES'][path[0]]['METHODS'] = {}
// Merge stacks if method exists
if (obj['ROUTES'][path[0]]['METHODS'][method]) {
value.stack = obj['ROUTES'][path[0]]['METHODS'][method].stack.concat(value.stack)
value.vars = UTILS.mergeObjects(obj['ROUTES'][path[0]]['METHODS'][method].vars,value.vars)
}
// Add/Update the method
obj['ROUTES'][path[0]]['METHODS'] = Object.assign(
{},obj['ROUTES'][path[0]]['METHODS'],{ [method]: value }
)
}
}
}
} // end setRoute
// Load app packages
app(packages) {
// Check for supplied packages
if (typeof packages === 'object') {
// Loop through and set package namespaces
for (let namespace in packages) {
try {
this._app[namespace] = packages[namespace]
} catch(e) {
console.error(e.message) // eslint-disable-line no-console
}
}
} else if (arguments.length === 2 && typeof packages === 'string') {
this._app[packages] = arguments[1]
}// end if
// Return a reference
return this._app
}
// Register routes with options
register(fn,opts) {
let options = typeof opts === 'object' ? opts : {}
// Extract Prefix
let prefix = options.prefix && options.prefix.toString().trim() !== '' ?
this.parseRoute(options.prefix) : []
// Concat to existing prefix
this._prefix = this._prefix.concat(prefix)
// Execute the routing function
fn(this,options)
// Remove the last prefix
this._prefix = this._prefix.slice(0,-(prefix.length))
} // end register
// prettyPrint debugger
routes(format) {
// Parse the routes
let routes = UTILS.extractRoutes(this._routes)
if (format) {
console.log(prettyPrint(routes)) // eslint-disable-line no-console
} else {
return routes
}
}
} // end API class
// Export the API class as a new instance
// module.exports = opts => new API(opts)