-
Notifications
You must be signed in to change notification settings - Fork 36
/
parameters.ts
658 lines (523 loc) · 15.6 KB
/
parameters.ts
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
import { ValidationError } from './exceptions'
import {
EnumerationParameterType,
ParameterBody,
ParameterLocation,
ParameterType,
RegexParameterType,
StringParameterType,
} from './types'
export class BaseParameter {
public static isParameter = true
public isParameter = true
type = 'string'
public params: ParameterType
public generated: boolean
constructor(params?: ParameterType) {
this.params = params || {}
this.generated = true
if (this.params.required === undefined) this.params.required = true
}
getValue() {
const value: Record<string, any> = {
type: this.type,
description: this.params.description,
example: this.params.example,
default: this.params.default,
}
if (this.params.deprecated) value.deprecated = this.params.deprecated
return value
}
validate(value: any): any {
return value
}
}
export class Arr extends BaseParameter {
public isArr = true
private innerType
constructor(innerType: any, params?: ParameterType) {
super(params)
this.innerType = innerType
}
validate(value: any): any {
value = super.validate(value)
if (this.params.required === false && (value === null || value === '')) {
return null
}
if (Array.isArray(value)) {
value = value.map((val) => {
return this.innerType.validate(val)
})
} else {
value = [this.innerType.validate(value)]
}
return value
}
// @ts-ignore
getValue() {
return {
type: 'array',
items: this.innerType.getValue(),
}
}
}
export class Obj extends BaseParameter {
public isObj = true
private fields: Record<string, BaseParameter>
constructor(fields: Record<string, BaseParameter>, params?: ParameterType) {
super(params) // TODO: fix obj params
this.fields = fields
}
validate(value: any): any {
value = super.validate(value)
for (const [key, param] of Object.entries(this.fields)) {
try {
if (value[key] === undefined || value[key] === null) {
if (param.params.required) {
throw new ValidationError('is required')
}
} else {
value[key] = param.validate(value[key])
}
} catch (e) {
// @ts-ignore
e.key = (e.key || '') + `.${key}`
throw e
}
}
return value
}
// @ts-ignore
getValue() {
const result: Record<string, any> = {
type: 'object',
properties: {},
}
const required = []
for (const [key, value] of Object.entries(this.fields)) {
if (value.params?.required === true) {
required.push(key)
}
if (value.getValue) {
result.properties[key] = value.getValue()
} else {
result.properties[key] = value
}
}
if (required.length > 0) {
result.required = required
}
return result
}
}
export class Num extends BaseParameter {
type = 'number'
validate(value: any): any {
value = super.validate(value)
value = Number.parseFloat(value)
if (isNaN(value)) {
throw new ValidationError('is not a valid number')
}
return value
}
}
export class Int extends Num {
type = 'integer'
validate(value: any): any {
value = super.validate(value)
value = Number.parseInt(value)
if (isNaN(value)) {
throw new ValidationError('is not a valid integer')
}
return value
}
}
export class Str extends BaseParameter {
type = 'string'
public declare params: StringParameterType
constructor(params?: StringParameterType) {
super(params)
}
validate(value: any): any {
value = super.validate(value)
if (typeof value !== 'string') {
value = value.toString()
}
if (this.params.format) {
if (this.params.format === 'date-time') {
value = new Date(value)
if (isNaN(value.getDay())) {
throw new ValidationError('is not a valid date time')
}
} else if (this.params.format === 'date') {
if (!value.match(/^[0-9]{4}-[0-9]{2}-[0-9]{2}$/)) {
throw new ValidationError('is not a valid date')
}
value = new Date(value)
if (isNaN(value.getDay())) {
throw new ValidationError('is not a valid date')
}
}
// TODO: validate remaining formats
}
return value
}
getValue() {
return {
...super.getValue(),
format: this.params.format,
}
}
}
export class DateTime extends Str {
type = 'string'
public declare params: StringParameterType
constructor(params?: StringParameterType) {
super({
example: '2022-09-15T00:00:00Z',
...params,
format: 'date-time',
})
}
}
export class Regex extends Str {
type = 'string'
public declare params: RegexParameterType
constructor(params: RegexParameterType) {
super(params)
}
validate(value: any): any {
value = super.validate(value)
if (!value.match(this.params.pattern)) {
if (this.params.patternError) {
throw new ValidationError(`is not a valid ${this.params.patternError}`)
}
throw new ValidationError(`does not match the pattern ${this.params.format}`)
}
return value
}
getValue() {
return {
...super.getValue(),
pattern: this.params.pattern,
}
}
}
export class Email extends Regex {
type = 'string'
public declare params: RegexParameterType
constructor(params?: StringParameterType) {
super({
pattern: '^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$',
patternError: 'email',
...params,
format: 'email',
})
}
}
export class Uuid extends Regex {
type = 'string'
public declare params: RegexParameterType
constructor(params?: StringParameterType) {
super({
pattern: '^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$',
patternError: 'uuid',
...params,
format: 'uuid',
})
}
}
export class Hostname extends Regex {
type = 'string'
public declare params: RegexParameterType
constructor(params?: StringParameterType) {
super({
pattern:
'^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\\-]*[a-zA-Z0-9])\\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\\-]*[A-Za-z0-9])$',
patternError: 'hostname',
...params,
format: 'hostname',
})
}
}
export class Ipv4 extends Regex {
type = 'string'
public declare params: RegexParameterType
constructor(params?: StringParameterType) {
super({
pattern: '^(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}$',
patternError: 'ipv4',
...params,
format: 'ipv4',
})
}
}
export class Ipv6 extends Regex {
type = 'string'
public declare params: RegexParameterType
constructor(params?: StringParameterType) {
super({
pattern:
'^(?:(?:[a-fA-F\\d]{1,4}:){7}(?:[a-fA-F\\d]{1,4}|:)|(?:[a-fA-F\\d]{1,4}:){6}(?:(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}|:[a-fA-F\\d]{1,4}|:)|(?:[a-fA-F\\d]{1,4}:){5}(?::(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}|(?::[a-fA-F\\d]{1,4}){1,2}|:)|(?:[a-fA-F\\d]{1,4}:){4}(?:(?::[a-fA-F\\d]{1,4}){0,1}:(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}|(?::[a-fA-F\\d]{1,4}){1,3}|:)|(?:[a-fA-F\\d]{1,4}:){3}(?:(?::[a-fA-F\\d]{1,4}){0,2}:(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}|(?::[a-fA-F\\d]{1,4}){1,4}|:)|(?:[a-fA-F\\d]{1,4}:){2}(?:(?::[a-fA-F\\d]{1,4}){0,3}:(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}|(?::[a-fA-F\\d]{1,4}){1,5}|:)|(?:[a-fA-F\\d]{1,4}:){1}(?:(?::[a-fA-F\\d]{1,4}){0,4}:(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}|(?::[a-fA-F\\d]{1,4}){1,6}|:)|(?::(?:(?::[a-fA-F\\d]{1,4}){0,5}:(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}|(?::[a-fA-F\\d]{1,4}){1,7}|:)))(?:%[0-9a-zA-Z]{1,})?$',
patternError: 'ipv6',
...params,
format: 'ipv6',
})
}
}
export class DateOnly extends Str {
type = 'string'
public declare params: StringParameterType
constructor(params?: StringParameterType) {
super({
example: '2022-09-15',
...params,
format: 'date',
})
}
}
export class Bool extends Str {
type = 'boolean'
private validValues = ['true', 'false']
validate(value: any): any {
value = super.validate(value)
value = value.toLowerCase()
if (!this.validValues.includes(value)) {
throw new ValidationError('is not a valid boolean, allowed values are true or false')
}
value = value === 'true'
return value
}
}
export class Enumeration extends Str {
public isEnum = true
public declare params: EnumerationParameterType
public values: Record<string, any>
public keys: any
constructor(params: EnumerationParameterType) {
super(params)
let { values } = params
if (Array.isArray(values)) values = Object.fromEntries(values.map((x) => [x, x]))
this.keys = Object.keys(values)
this.values = values
}
validate(value: any): any {
value = super.validate(value)
if (this.params.enumCaseSensitive !== false) {
value = this.params.values[value]
} else {
const key = this.keys.find((key: any) => key.toLowerCase() === value.toLowerCase())
value = this.params.values[key]
}
if (value === undefined) {
if (this.params.required === true) {
throw new ValidationError('is not one of available options')
}
// Parameter not required neither one of the available options
return null
}
return value
}
getValue() {
return {
...super.getValue(),
enum: this.keys,
}
}
}
export class Parameter {
public location: string
private rawType: any
public type: BaseParameter
public params: ParameterLocation
constructor(location: string, rawType: any, params: ParameterLocation) {
this.location = location
this.rawType = rawType
if (params.required === undefined) params.required = true
this.params = params
this.type = this.getType(rawType, params)
}
getType(type: any, params: ParameterLocation): any {
if (type.generated === true) {
return type
}
if (type.isParameter === true) {
// @ts-ignore
return new type({ ...params })
}
if (type === String) {
return new Str({ ...params })
}
if (typeof type === 'string') {
return new Str({ example: type })
}
if (type === Number) {
return new Num({ ...params })
}
if (typeof type === 'number') {
return new Num({ example: type })
}
if (type === Boolean) {
return new Bool({ ...params })
}
if (typeof type === 'boolean') {
return new Bool({ example: type })
}
if (type === Date) {
return new DateTime()
}
if (Array.isArray(type)) {
if (type.length === 0) {
throw new Error('Arr must have a type')
}
return new Arr(this.getType(type[0], params), { ...params })
}
if (typeof type === 'object') {
const parsed: Record<string, any> = {}
for (const [key, value] of Object.entries(type)) {
parsed[key] = this.getType(value, {})
}
return new Obj(parsed, params)
}
throw new Error(`${type} not implemented`)
}
getValue(): Record<string, any> {
const schema = removeUndefinedFields(this.type.getValue())
return {
description: this.params.description,
required: this.params.required,
schema: schema,
name: this.params.name,
in: this.location,
}
}
validate(value: any): any {
if (value === undefined || value === null) {
if (this.params.default !== undefined && this.params.default !== null) {
value = this.params.default
} else {
if (this.params.required) {
throw new ValidationError('is required')
} else {
return null
}
}
}
value = this.type.validate(value)
return value
}
}
export class Body extends Parameter {
paramsBody: ParameterBody
constructor(rawType: any, params?: ParameterBody) {
// @ts-ignore
super(null, rawType, {})
// @ts-ignore
this.paramsBody = params
}
getValue(): Record<string, any> {
const schema = removeUndefinedFields(this.type.getValue())
const param: Record<string, any> = {
description: this.paramsBody?.description,
content: {},
}
param.content[this.paramsBody?.contentType || 'application/json'] = { schema: schema }
return param
}
}
export class Resp extends Parameter {
constructor(rawType: any, params: ParameterLocation) {
// @ts-ignore
super(null, rawType, params)
}
// @ts-ignore
getValue() {
const value = super.getValue()
const contentType = this.params?.contentType ? 'this.params?.contentType' : 'application/json'
const param: Record<string, any> = {
description: this.params.description || 'Successful Response',
content: {},
}
param.content[contentType] = { schema: value.schema }
return param
}
}
export function Query(type: any, params: ParameterLocation = {}): Parameter {
return new Parameter('query', type, params)
}
export function Path(type: any, params: ParameterLocation = {}): Parameter {
return new Parameter('path', type, params)
}
export function Header(type: any, params: ParameterLocation = {}): Parameter {
return new Parameter('header', type, params)
}
export function Cookie(type: any, params: ParameterLocation = {}): Parameter {
return new Parameter('cookie', type, params)
}
export function extractParameter(request: Request, query: Record<string, any>, name: string, location: string): any {
if (location === 'query') {
return query[name]
}
if (location === 'path') {
// @ts-ignore
return request.params[name]
}
if (location === 'header') {
// @ts-ignore
return request.headers.get(name)
}
if (location === 'cookie') {
throw new Error('Cookie parameters not implemented yet')
}
}
export function extractQueryParameters(request: Request): Record<string, any> {
const url = decodeURIComponent(request.url).split('?')
if (url.length === 1) {
return {}
}
const query = url[1]
const params: Record<string, any> = {}
for (const param of query.split('&')) {
const paramSplitted = param.split('=')
const key = paramSplitted[0]
const value = paramSplitted[1]
if (params[key] === undefined) {
params[key] = value
} else if (!Array.isArray(params[key])) {
params[key] = [params[key], value]
} else {
params[key].push(value)
}
}
return params
}
export function Required(param: Parameter): Parameter {
param.params.required = true
return param
}
export function removeUndefinedFields(obj: Record<string, any>): Record<string, any> {
for (const [key, value] of Object.entries(obj)) {
if (typeof value === 'object' && !Array.isArray(value)) obj[key] = removeUndefinedFields(value)
if (value === undefined) {
delete obj[key]
}
}
return obj
}
export function getFormatedParameters(params: Record<string, Parameter> | Parameter[]) {
const formated = []
const isArray = Array.isArray(params)
for (const [key, parameter] of Object.entries(params || {})) {
if (isArray && !parameter.params.name) {
throw new Error('Parameter must have a defined name when using as Array')
}
const name = parameter.params.name ? parameter.params.name : key
formated.push({
// TODO: check this type before assign
// @ts-ignore
...parameter.getValue(),
name: name,
})
}
return formated
}