-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlib.js
766 lines (704 loc) · 19.8 KB
/
lib.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
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
// Copyright (c) 2020 Alexandru Catrina <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
'use strict'
/**
* Wildcard char to lookup any item from a dataset.
*
* @type {string}
*/
const WILDCARD = '*'
/**
* Capture all placeholders from content.
*
* @param {string} content The content to parse
* @returns {Generator}
*/
function * capture (content) {
let placeholder
const regex = /\{{1}([a-z0-9\.\-_]+)\}{1}/ig
while ((placeholder = regex.exec(content)) !== null) {
yield placeholder[1]
}
}
/**
* Interpret a given string to generate content from context.
*
* @param {string} text The string to interpret
* @param {RequestContextObject} ctx The available context
* @param {boolean} lower Optional flag to lowercase variable
* @returns {string}
*/
function interpret (text, ctx, lower = false) {
const cm = new ContextManager(ctx)
for (const variable of capture(text)) {
const needle = lower ? variable.toLowerCase() : variable
const value = cm.get(needle)
if (value !== null) {
text = text.replace(`{${variable}}`, value)
}
}
return text
}
/**
* Generate random content and interpret placeholders.
*
* @param {string} data Serialized data
* @param {CallableFunction?} tf Callback to format text
* @returns {string|string[]|object|object[]}
*/
function generateContent (data, tf = null) {
const content = JSON.parse(data)
if (Array.isArray(content)) {
for (let i = 0; i < content.length; i++) {
content[i] = generateContent(JSON.stringify(content[i]), tf)
}
return content
} else if (typeof content === 'object' && content.constructor === Object) {
Object.entries(content).forEach(([k, v]) => {
content[k] = generateContent(JSON.stringify(v), tf)
})
return content
}
const textContent = content.toString()
return tf instanceof Function ? tf(textContent) : textContent
}
/**
* Repeat the elements of a list by a fixed or random number from a range.
*
* @param {any[]} list Anything iterable
* @param {string} formula Repeat formula to apply
* @return {any[]}
*/
function repeatContent (list, formula) {
let total
if (formula.indexOf('..') > -1) {
const [min, max] = formula.split('..', 2)
const minValue = parseInt(min, 10) || list.length
const maxValue = parseInt(max, 10) || list.length
total = Math.floor(Math.random() * (maxValue - minValue + 1) + minValue)
} else {
total = parseInt(formula.toString(), 10)
}
const stack = new Array()
for (let i = 0; i < total; i++) {
stack.push(list)
}
return [].concat(...stack)
}
/**
* Cast given field(s) into a datatype of user choice from a source.
*
* @param {string} type The datatype to cast into
* @param {any} value The raw value to cast
* @returns {number|boolean|string}
*/
function castContent (type, value) {
if (typeof value === 'undefined' || value === null) {
return `<cannot cast "${value}" as ${type}>`
} else if (type === 'number') {
const num = Number(value.toString())
if (isNaN(num)) {
return `<"${value}" is not a number>`
}
return num
} else if (type === 'boolean') {
if (value.toString().toLowerCase() === 'true') {
return true
} else if (value.toString().toLowerCase() === 'false') {
return false
} else {
return `<"${value}" is not a boolean>`
}
} else if (type === 'string') {
return value.toString()
}
throw new Error(`Unsupported cast type "${type}"`)
}
/**
* The context manager is responsable to retrieve and change any existing or
* non-existing information from a source of the user's choice. It is mostly
* used by the content generator/interpretor.
*/
class ContextManager {
/**
* Initialize context manager.
*
* @param {object} src Source as context to manage
*/
constructor (src) {
this.ctx = src
}
/**
* Shorthand method to get the content of a field.
*
* @param {string} field
* @returns {any}
*/
get (field) {
return ContextManager.read(this.ctx, field.split('.'))
}
/**
* Shorthand method to set the content for a field.
*
* @param {string} field
* @param {any} data
* @returns void
*/
set (field, data) {
ContextManager.write(this.ctx, field.split('.'), data)
}
/**
* Lookup and retrieve the value of a field from a heystack.
*
* NOTE: *this* in static methods is not the reference variable,
* but instead it's the class itself...
*
* @param {any} source Heystack source pool
* @param {string[]} fieldpath Needle to lookup
* @returns {any}
*/
static read (source, fieldpath) {
const field = fieldpath.shift()
if (field === undefined) {
return source
}
if (field === WILDCARD && Array.isArray(source)) {
const dataset = []
for (const each of source) {
const value = this.read(each, [...fieldpath])
if (value !== null) {
dataset.push(value)
}
}
return dataset
}
const results = source[field] || null // NOTE: avoid undefined
if (results === null) {
return null
} else if (results.constructor === Object || Array.isArray(results)) {
return this.read(results, fieldpath)
} else {
return results
}
}
/**
* Lookup and store the value of a field on a heystack.
*
* NOTE: *this* in static methods is not the reference variable,
* but instead it's the class itself...
*
* @param {any} source Heystack source
* @param {string[]} fieldpath Needle to lookup
* @param {CallableFunction} content Content callback
* @returns any
*/
static write (source, fieldpath, content) {
const field = fieldpath.shift()
if (field === undefined) {
return content(source)
} else {
if (field === WILDCARD && Array.isArray(source)) {
for (let i = 0; i < source.length; i++) {
source[i] = this.write(source[i], [...fieldpath], content)
}
} else if (field in source) {
source[field] = this.write(source[field], fieldpath, content)
} else {
source[field] = content(undefined)
}
}
return source
}
}
/**
* Base handler class, with basic validation methods for common fields
* on both requests and responses.
*/
class CommonHandler {
/**
* Check if the HTTP headers are correct.
*
* @param {object} headers The headers to validate
* @throws {Error} Duplicated headers not allowed
* @returns {object?}
*/
_validateHeaders (headers) {
if (headers === undefined) {
return {}
}
const lowercaseHeaders = {}
for (const [k, v] of Object.entries(headers)) {
const key = k.toLowerCase()
if (key in lowercaseHeaders) {
throw new Error(`Duplicated headers not allowed: ${k}/${key}`)
}
lowercaseHeaders[key] = v // NOTE: Element implicitly is any type?
}
return lowercaseHeaders
}
}
/**
* Request Object Interface.
*
* @type {{
* route: string,
* method: string,
* query: object,
* payload: object,
* headers: object,
* }}
*/
const RequestObject = {
route: 'endpoint with optional {placeholder(s)}',
method: 'head | get | post | put | patch | delete',
query: {
param1: 'value or {placeholder}',
param2: ['value', '{placeholder}']
},
payload: {
field1: 'value or {placeholder}',
field2: {
subfield: 'value or {placeholder}'
}
},
headers: {
'X-Some-Header1': 'value or {placeholder}',
'X-Some-Header2': 'value or {placeholder}'
}
}
/**
* Request object handler performs first-level validations for user errors
* and extracts required fields to launch the API server (e.g. routes). It
* also encapsulates all request-related content for later use by the REST
* API generator.
*/
class RequestHandler extends CommonHandler {
/**
* Initialize request handler.
*
* @param {RequestObject} r The request object to handle
*/
constructor ({ method, route, headers, query, payload }) {
super()
this.method = this._validateHttpRouteMethod(method)
this.route = this._validateHttpRoute(route)
this.query = this._validateQueryString(query)
this.headers = this._validateHeaders(headers)
this.payload = this._validatePayload(payload)
}
/**
* Check if the query string is valid.
*
* @param {object} query The query string to validate
* @throws {Error} Query string must be string or string[]
* @returns {object?}
*/
_validateQueryString (query) {
if (query === undefined) {
return {}
}
if (query && typeof query === 'object' && query.constructor === Object) {
Object.entries(query).forEach(([key, value]) => {
if (!Array.isArray(value)) {
value = [value]
}
for (const each of value) {
if (each.toString() !== each) {
throw new Error(`Query string "${key}" must be string or string[]`)
}
}
})
} else {
throw new Error(`Request query must be object, got ${typeof query}`)
}
return query
}
/**
* Check if the request payload has a correct format. It can either an
* object with key-value pairs of information submitted as JSON object
* or URL encoded equivalents; or a buffer submitted as string (base64
* preferred, but limited to).
*
* @param {object|string} payload The payload to validate
* @throws {Error} Request payload must be an object or a string
* @returns {object|string|null}
*/
_validatePayload (payload) {
if (payload === undefined) {
return null
}
if (typeof payload === 'object' && payload.constructor === Object) {
return payload
} else if (payload && payload.toString() === payload) {
return payload
}
throw new Error('Request payload must be an object or a string')
}
/**
* Check if the request endpoint is set.
*
* @param {string} route The route to validate
* @throws {Error} Request route must be a non-empty string
* @returns {string}
*/
_validateHttpRoute (route) {
if (!route || route.trim().length === 0) {
throw new Error('Request route must be a non-empty string')
}
return route
}
/**
* Check if the request method is set to a supported RESTful verb.
*
* @param {string} method The HTTP method to validate
* @throws {Error} Unsupported HTTP method
* @returns {string}
*/
_validateHttpRouteMethod (method) {
if (RequestHandler.HTTP_VERBS.indexOf(method.toLowerCase()) === -1) {
throw new Error(`Unsupported request HTTP method: ${method}`)
}
return method.toLowerCase()
}
/**
* Supported HTTP verbs.
*
* @type {string[]}
*/
static get HTTP_VERBS () {
return ['head', 'get', 'post', 'put', 'patch', 'delete']
}
/**
* String representation of RequestHandler instance.
*
* @returns {string}
*/
toString () {
return `${this.method.toUpperCase()} ${this.route}`
}
}
/**
* Response Metadata Object Interface.
*
* @type {{
* cast: Record<string, string>,
* repeat: string
* }}
*/
const ResponseMetadataObject = {
cast: {
id: 'number',
'books.*': 'number'
},
repeat: '..20'
}
/**
* Response Object Interface.
*
* @type {{
* code: string,
* headers: object,
* data: object|object[]|string|string[],
* $data: ResponseMetadataObject?
* }}
*/
const ResponseObject = {
code: 'valid HTTP status code',
headers: {
'Powered-By': 'Samplest'
},
data: {
id: 'generated value or {placeholder}',
username: 'generated value or {placeholder}',
books: [
'generated value 1',
'generated value 2'
]
},
$data: {
cast: {
'key from data': 'number | boolean | string (default)'
},
repeat: 'any positive number or [min..max]'
}
}
/**
* Response object handler performs first-level validations for user errors
* and evaluates placeholders used in "headers" or "data", according to the
* metafield configuration ($data).
*/
class ResponseHandler extends CommonHandler {
/**
* Initialize response handler.
*
* @param {ResponseObject} r The response object to handle
*/
constructor ({ code, headers, data, $data }) {
super()
this.code = this._validateStatusCode(code)
this.headers = this._validateHeaders(headers)
this.data = data || null // NOTE: avoid undefined
this.$data = $data && this._validateMetadata($data)
}
/**
* Supported cast options.
*
* @type {string[]}
*/
static get CAST_OPTIONS () {
return ['number', 'boolean', 'string']
}
/**
* Check if the metadata fields are supported.
*
* @param {ResponseMetadataObject} $data The metadata to validate
* @returns {ResponseMetadataObject?}
*/
_validateMetadata ($data) {
if ($data && typeof $data === 'object' && $data.constructor === Object) {
const { cast, repeat } = $data
if (cast && typeof cast === 'object') {
this._validateMetadataCastTypes(cast)
} else if (typeof cast !== 'undefined') {
throw new Error('Cast must be a key-value object')
}
if (repeat && repeat.toString() === repeat) {
this._validateMetadataRepeatOptions(repeat)
} else if (typeof repeat !== 'undefined') {
throw new Error('Repeat must be a string')
}
}
return $data
}
/**
* Helper method to validate metadata repeat options.
*
* @param {string} repeat The repeat formula as string
* @throws {Error} Cannot use meta repeat on a non-array data
* @throws {Error} Invalid repeat options: min(MIN) max(MAX)
* @returns void
*/
_validateMetadataRepeatOptions (repeat) {
if (!Array.isArray(this.data)) {
throw new Error('Cannot use meta repeat on a non-array data')
}
if (repeat.indexOf('..') === -1) {
const nth = parseInt(repeat, 10)
if (isNaN(nth)) {
throw new Error(`Invalid repeat number: ${repeat}`)
}
} else {
let [min, max] = repeat.split('..', 2)
min = min || this.data.length.toString()
max = max || this.data.length.toString()
const minValue = parseInt(min, 10)
const maxValue = parseInt(max, 10)
if (isNaN(minValue) || isNaN(maxValue)) {
throw new Error(`Invalid repeat options: min(${min}) max(${max})`)
}
}
}
/**
* Helper method to validate metadata cast types.
*
* @param {Record<string, string>} cast Key-value pairs of properties
* @throws {Error} Nothing to cast
* @throws {Error} Unsupported cast type
* @returns void
*/
_validateMetadataCastTypes (cast) {
if (this.data === null || typeof this.data !== 'object') {
throw new Error('Casting works only with response data objects')
}
const ctx = new ContextManager(this.data)
Object.keys(cast).forEach(key => {
const value = ctx.get(key)
if (value === null) {
throw new Error(`Nothing to cast on ${key}`)
}
if (ResponseHandler.CAST_OPTIONS.indexOf(cast[key]) === -1) {
throw new Error(`Unsupported cast type: ${cast[key]}`)
}
})
}
/**
* Check if the response code is an HTTP status code.
*
* @param {string} code The status code to validate
* @throws {Error} Response HTTP status code invalid
* @throws {Error} Unsupported response HTTP status code
* @returns void
*/
_validateStatusCode (code) {
const statusCode = parseInt(code.toString())
if (isNaN(statusCode)) {
throw new Error(`Response HTTP status code invalid: ${code}`)
} else if (statusCode < 100 || statusCode > 599) {
throw new Error(`Unsupported response HTTP status: ${statusCode}`)
}
return code
}
/**
* String representation of ResponseHandler instance.
*
* @return {string}
*/
toString () {
return `${this.code}`
}
}
/**
* Except Case Object Interface.
*
* @type {{
* validate: string[],
* response: ResponseObject
* }}
*/
const ExceptCaseObject = {
validate: [
'js code as one line of string',
'js code as one line of string'
],
response: {
code: 'number',
headers: {
'X-Header': 'string'
},
data: 'string | string[] | object | object[]',
$data: null
}
}
/**
* Except Object Interface.
*
* @type {Record<string, ExceptCaseObject>}
*/
const ExceptObject = {
'Assert message goes here': {
validate: [
'first function body to test',
'second function body to test'
],
response: {
code: '400',
headers: {
'X-Reject-Reason': 'Exception rule failure'
},
data: 'feedback message',
$data: null
}
}
}
/**
* Except object handler (optional middleware) performs custom tests as one
* lines of JavaScript code, isolated from the rest of the application with
* only the current context available to use as parameters. Upon failure it
* overrides the response with the current exception's case.
*/
class ExceptHandler {
/**
* Initialize rules handler.
*
* @param {ExceptObject} except The exceptions to handle
*/
constructor (except) {
this.cases = this._validate(except)
}
/**
* Check if the except cases object is properly formatted.
*
* @param {Record<string, ExceptCaseObject>} cases Except cases object to validate
* @retusns {Record<string, ExceptCaseObject>}
*/
_validate (cases) {
if (cases && typeof cases === 'object' && cases.constructor === Object) {
for (const [assertion, { validate, response }] of Object.entries(cases)) {
if (!Array.isArray(validate) || validate.length === 0) {
throw new Error(`Except case "${assertion}" field "validate" ` +
`must be string[], got ${typeof validate}`)
}
for (let i = 0; i < validate.length; i++) {
const test = validate[i]
if (test.toString() !== test) {
throw new Error(`Except case "${assertion}" field "validate" ` +
`must be string on position ${i}, got ${typeof test} instead`)
}
}
try {
const rh = new ResponseHandler(response)
if (!rh) {
throw new Error('Failed to create response handler from except')
}
} catch (e) {
throw new Error(`Except case "${assertion}" field "response" ` +
`incompatible with Response Object Interface: ${e.message}`)
}
}
}
return cases
}
}
/**
* Incoming request context interface.
*
* @type {{
* time: string,
* route: object,
* query: object,
* headers: object,
* payload: object,
* }}
*/
const RequestContextObject = {
time: '0000000000',
route: {
username: 'lexndru'
},
query: {
per_page: '10',
limit: '50'
},
headers: {
'X-Header1': 'abc',
'X-Header2': 'def'
},
payload: {
projectName: 'samplest',
projectDesc: 'mockup api from cli'
}
}
module.exports = {
castContent,
repeatContent,
generateContent,
capture,
interpret,
ContextManager,
RequestObject,
RequestHandler,
RequestContextObject,
ResponseObject,
ResponseMetadataObject,
ResponseHandler,
ExceptObject,
ExceptCaseObject,
ExceptHandler
}