-
Notifications
You must be signed in to change notification settings - Fork 126
/
index.js
557 lines (475 loc) · 16 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
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
'use strict';
/**
* Lightweight web framework for your serverless applications
* @author Jeremy Daly <[email protected]>
* @license MIT
*/
const REQUEST = require('./lib/request');
const RESPONSE = require('./lib/response');
const UTILS = require('./lib/utils');
const LOGGER = require('./lib/logger');
const S3 = () => require('./lib/s3-service');
const prettyPrint = require('./lib/prettyPrint');
const { ConfigurationError } = require('./lib/errors');
class API {
constructor(props) {
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;
this._errorHeaderWhitelist =
props && Array.isArray(props.errorHeaderWhitelist)
? props.errorHeaderWhitelist.map((header) => header.toLowerCase())
: [];
this._isBase64 =
props && typeof props.isBase64 === 'boolean' ? props.isBase64 : false;
this._headers =
props && props.headers && typeof props.headers === 'object'
? props.headers
: {};
this._compression =
props &&
(typeof props.compression === 'boolean' ||
Array.isArray(props.compression))
? props.compression
: false;
this._s3Config = props && props.s3Config;
// Set S3 Client
if (this._s3Config) S3().setConfig(this._s3Config);
this._sampleCounts = {};
this._requestCount = 0;
this._initTime = Date.now();
this._logLevels = {
trace: 10,
debug: 20,
info: 30,
warn: 40,
error: 50,
fatal: 60,
};
this._logger = LOGGER.config(props && props.logger, this._logLevels);
// Prefix stack w/ base
this._prefix = this.parseRoute(this._base);
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;
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);
});
}
// 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 methods is an array and upper case
let methods = (Array.isArray(method) ? method : method.split(',')).map(
(x) => (typeof x === 'string' ? x.trim().toUpperCase() : null)
);
// 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 = { '*': [], m: [] };
// Loop through the path levels
for (let i = 0; i < route.length; i++) {
// Flag as end of the path
let end = i === route.length - 1;
// If this is a parameter 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
// Create routes and add path if they don't exist
if (!routes['ROUTES']) {
routes['ROUTES'] = {};
}
if (!routes['ROUTES'][route[i]]) {
routes['ROUTES'][route[i]] = {};
}
// Loop through methods for the route
methods.forEach((_method) => {
// Method must be a string
if (typeof _method === 'string') {
// Check for wild card at this level
if (routes['ROUTES']['*']) {
if (
routes['ROUTES']['*']['MIDDLEWARE'] &&
(route[i] !== '*' || _method !== '__MW__')
) {
_stack['*'][method] = routes['ROUTES']['*']['MIDDLEWARE'].stack;
}
if (
routes['ROUTES']['*']['METHODS'] &&
routes['ROUTES']['*']['METHODS'][method]
) {
_stack['m'][method] =
routes['ROUTES']['*']['METHODS'][method].stack;
}
} // end if wild card
// If this is the end of the path
if (end) {
// Check for matching middleware
if (
route[i] !== '*' &&
routes['ROUTES'][route[i]] &&
routes['ROUTES'][route[i]]['MIDDLEWARE']
) {
_stack['m'][method] =
routes['ROUTES'][route[i]]['MIDDLEWARE'].stack;
} // end if
// Generate the route/method meta data
let meta = {
vars: pathVars,
stack: _stack['m'][method]
? _stack['m'][method].concat(stack)
: _stack['*'][method]
? _stack['*'][method].concat(stack)
: stack,
// inherited: _stack[method] ? _stack[method] : [],
route: '/' + parsedPath.join('/'),
path: '/' + this._prefix.concat(parsedPath).join('/'),
};
// If mounting middleware
if (method === '__MW__') {
// Merge stacks if middleware exists
if (routes['ROUTES'][route[i]]['MIDDLEWARE']) {
meta.stack =
routes['ROUTES'][route[i]]['MIDDLEWARE'].stack.concat(stack);
meta.vars = UTILS.mergeObjects(
routes['ROUTES'][route[i]]['MIDDLEWARE'].vars,
pathVars
);
}
// Add/update middleware
routes['ROUTES'][route[i]]['MIDDLEWARE'] = meta;
// Apply middleware to all child middlware routes
// if (route[i] === "*") {
// // console.log("APPLY NESTED MIDDLEWARE");
// // console.log(JSON.stringify(routes["ROUTES"], null, 2));
// Object.keys(routes["ROUTES"]).forEach((nestedRoute) => {
// if (nestedRoute != "*") {
// console.log(nestedRoute);
// }
// });
// }
} else {
// Create the methods section if it doesn't exist
if (!routes['ROUTES'][route[i]]['METHODS'])
routes['ROUTES'][route[i]]['METHODS'] = {};
// Merge stacks if method already exists for this route
if (routes['ROUTES'][route[i]]['METHODS'][_method]) {
meta.stack =
routes['ROUTES'][route[i]]['METHODS'][_method].stack.concat(
stack
);
meta.vars = UTILS.mergeObjects(
routes['ROUTES'][route[i]]['METHODS'][_method].vars,
pathVars
);
}
// Add method and meta data
routes['ROUTES'][route[i]]['METHODS'][_method] = meta;
} // end else
// console.log('STACK:',meta);
// If there's a wild card that's not at the end
} else if (route[i] === '*') {
throw new ConfigurationError(
'Wildcards can only be at the end of a route definition'
);
} // end if end of path
} // end if method is string
}); // end methods loop
// Update the current routes pointer
routes = routes['ROUTES'][route[i]];
} // end path traversal loop
// console.log(JSON.stringify(this._routes,null,2));
} // 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;
// eslint-disable-next-line
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) {
// console.log(e);
await this.catchErrors(e, 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 respect the app's base64 configuration
response._isBase64 = this._isBase64;
// Strip the headers, keep whitelist
const strippedHeaders = Object.entries(response._headers).reduce(
(acc, [headerName, value]) => {
if (!this._errorHeaderWhitelist.includes(headerName.toLowerCase())) {
return acc;
}
return Object.assign(acc, { [headerName]: value });
},
{}
);
response._headers = Object.assign(strippedHeaders, this._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;
if (this._logger.errorLogging) {
this.log.fatal(message, info);
}
} else {
message = e;
if (this._logger.errorLogging) {
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
// TODO: using async within a promise is an antipattern, therefore we need to refactor this asap
// eslint-disable-next-line no-async-promise-executor
await new Promise(async (r) => {
let rtn = await err(e, response._request, response, () => {
r();
});
if (rtn) response.send(rtn);
r();
});
} // 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) => {
this._logger.logger(
JSON.stringify(
this._logger.detail
? 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,
}
);
this._logger.logger(
JSON.stringify(this._logger.format(access, response._request, response))
);
}
// 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 for all methods
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() !== '');
}
// 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 (if a prefix exists)
if (prefix.length > 0) {
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);
// Add createAPI as default export (to match index.d.ts)
module.exports.default = module.exports;