| 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
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913 | 1x
1x
1x
1x
1x
1x
1x
1x
1x
1x
1x
18x
18x
18x
2x
2x
4x
1x
66x
18x
48x
1x
1x
1x
3x
1x
10x
10x
10x
10x
10x
10x
10x
10x
5x
5x
1x
4x
4x
4x
1x
4x
1x
1x
1x
3x
1x
17x
13x
1x
12x
4x
16x
16x
16x
14x
11x
11x
11x
1x
10x
5x
5x
5x
4x
1x
2x
1x
2x
2x
3x
3x
3x
3x
3x
2x
2x
2x
2x
3x
1x
1x
1x
1x
1x
1x
63x
63x
26x
4x
95x
4x
39x
39x
39x
39x
39x
39x
34x
4x
63x
2x
2x
1x
2x
1x
2x
1x
1x
8x
35x
2x
33x
33x
3x
30x
19x
11x
5x
6x
3x
3x
2x
2x
1x
2x
2x
1x
1x
16x
16x
16x
16x
16x
16x
1x
1x
70x
3x
67x
1x
66x
40x
26x
14x
12x
7x
7x
5x
5x
4x
5x
5x
1x
1x
8x
8x
1x
7x
7x
7x
7x
7x
7x
7x
19x
7x
15x
15x
27x
27x
15x
15x
52x
5x
5x
5x
3x
13x
8x
14x
14x
8x
8x
8x
2x
6x
4x
2x
2x
1x
| import * as classTransformer from 'class-transformer'
import * as classValidator from 'class-validator'
import * as fs from 'fs'
import { archivist } from 'mage'
import * as mage from 'mage'
import * as path from 'path'
const functionArguments = require('function-arguments')
const isObject = require('isobject')
const deepIterator = require('deep-iterator').default
const { Tome, ObjectTome, ArrayTome } = mage.require('tomes')
import 'reflect-metadata'
import * as classValidatorError from 'class-validator/validation/ValidationError'
/**
* Validation error classes
*
* Will contain all the validation errors that were found upon validation.
*
* @export
* @class ValidationError
* @extends {Error}
*/
export class ValidationError extends Error {
public details: any[]
constructor(message: string, details: any) {
super(message)
this.details = details
this.name = 'ValidationError'
}
}
/**
* Log emergency and crash
*
* @param {string} message
* @param {*} data
*/
function crash(message: string, data: any) {
mage.logger.emergency.data(data).log(message)
return new Error(message)
}
/**
* Throw only if the error is not "file/folder not found"
*
* @param {NodeJS.ErrnoException} error
*/
function throwIfNotFileNotFoundError(error: NodeJS.ErrnoException) {
if (error.code !== 'ENOENT') {
throw error
}
}
/**
* Throw on validation if at least one error is found
*
* @param {Error[]} errors
* @param {*} obj
* @returns
*/
function throwOnError(message: string, errors: classValidatorError.ValidationError[], obj?: any) {
if (errors.length > 0) {
throw new ValidationError(message, errors)
}
return obj
}
/**
* usercommand.execute function signature
*
* @export
* @interface IExecuteFunction
*/
type IExecuteFunction = <T>(state: mage.core.IState, ...args: any[]) => Promise<T>
/**
* Load topics from each module's 'topics' folder
*
* This function is a helper you will use in your project's
* `lib/archivist/index.js` file, as follow:
*
* ```typescript
* import { loadTopicsFromModules } from 'mage-validator'
*
* loadTopicsFromModules(exports)
* ```
*
* This will:
*
* - Find all your projetc's modules
* - For each module folders, check if there is a `topics` folder
* - When a `topics` folder is found, require each file in it
* - Add the content of the require to exports[fileNameWithoutJSExtension]
*
* @export
* @param {*} exports
*/
export function loadTopicsFromModules(exports: any) {
const modules = mage.listModules()
for (const moduleName of modules) {
loadTopicsFromModule(exports, moduleName)
}
}
/**
* Load topics defined in a single module
*
* @param {*} exports
* @param {string} moduleName
*/
export function loadTopicsFromModule(archivistExports: any, moduleName: string) {
const modulePath = mage.getModulePath(moduleName)
const moduleTopicsPath = path.join(modulePath, 'topics')
try {
fs.readdirSync(moduleTopicsPath).forEach(function (topicFileName) {
const topicPath = path.join(moduleTopicsPath, topicFileName)
const topicPathInfo = path.parse(topicPath)
const topicName = topicPathInfo.name
// Skip all files but TypeScript source files
if (topicPathInfo.ext !== '.ts') {
return
}
if (archivistExports[topicName]) {
throw crash('Topic is already defined!', {
alreadySetByModule: archivistExports[topicName]._module,
module: moduleName,
topic: topicName,
})
}
// Add topic to the export of lib/archivist/index.ts
const topic = archivistExports[topicName] = require(topicPath).default
topic._module = moduleName
// No explicit class name defined; we assign the name of the file as
// the class name used internally within the topic's methods
if (topic.getClassName().substring(0, 8) === 'default_') {
topic.setClassName(topicName)
}
})
} catch (error) {
throwIfNotFileNotFoundError(error)
}
}
/**
* The IStaticThis interface is required
* for us to be able to create static factory functions
* that return a properly typed output.
*/
export interface IStaticThis<T> {
new (): T,
getClassName(): string,
execute<T, R>(
this: IStaticThis<T>,
state: any,
method: any,
args: any[],
run: (data: any) => any): Promise<R>,
create<T extends ValidatedTopic>(
this: IStaticThis<T>,
state: mage.core.IState,
index: archivist.IArchivistIndex,
data?: any): Promise<T>,
get<T extends ValidatedTopic>(
this: IStaticThis<T>,
state: mage.core.IState,
indexes: archivist.IArchivistIndex,
options?: archivist.IArchivistGetOptions): Promise<T>
mget<T extends ValidatedTopic>(
this: IStaticThis<T>,
state: mage.core.IState,
indexes: archivist.IArchivistIndex[],
options?: archivist.IArchivistGetOptions): Promise<T[]>
}
/**
* Validated topic
*
* Please note that you should import the default
* of this module, not this class directly.
*
* Good:
*
* ```typescript
* import ValidatedTopic from 'mage-validator'
* ```
*
* Bad:
*
* ```typescript
* import { ValidatedTopic } from 'mage-validator'
* ```
*
* While the second line will work, it will provide you with
* less type safety than the first import example.
*
* @export
* @abstract
* @class ValidatedTopic
*/
export class ValidatedTopic {
public static readonly mediaType: string = 'application/json'
public static readonly index: string[]
public static readonly indexType: any
public static readonly vaults = {}
private static _className: string
/**
* Return the current class name
*
* @static
* @returns
*
* @memberof ValidatedTopic
*/
public static getClassName(): string {
/* istanbul ignore next */
if (!this._className) {
return this.toString().split ('(' || /s+/)[0].split (' ' || /s+/)[1]
}
return this._className
}
/**
* Explicitly set the name of this class
*
* @static
* @param {string} name
*
* @memberof ValidatedTopic
*/
public static setClassName(name: string): void {
this._className = name
}
/**
* Create an instance from a generic object
*
* @static
* @param {mage.core.IState} state
* @param {*} data
* @returns
*
* @memberof ValidatedTopic
*/
public static async create<T extends ValidatedTopic>(
this: IStaticThis<T>,
state: mage.core.IState,
index: archivist.IArchivistIndex,
data?: any): Promise<T> {
let instance
if (data) {
if (!isObject(data)) {
throw new Error(`Received data is not an object (received ${JSON.stringify(data)})`)
}
instance = classTransformer.plainToClass<T, object>(this, data)
} else {
instance = new this()
}
instance.setTopic(this.getClassName())
instance.setState(state)
await instance.setIndex(index)
return instance
}
/**
* Utility method used to promisify archivist calls
*
* @static
* @param {*} state
* @param {*} method
* @param {any[]} args
* @param {Function} run
* @returns
*
* @memberof ValidatedTopic
*/
public static async execute<T, R>(
this: IStaticThis<T>,
state: any,
method: any,
args: any[],
run: (data: any) => any): Promise<R> {
return new Promise<R>((resolve, reject) => {
state.archivist[method](...args, (error: Error, data: T) => {
if (error) {
return reject(error)
}
resolve(run(data))
})
})
}
/**
* Get a topic instance from backend vault(s)
*
* Mostly a wrapper around state.archivist.get. Note that
* instead of using the `optional` option directly with this call,
* you should consider using `tryGet` instead, which will trigger a
* compile error if you do not check for an undefined return value.
*
* @static
* @param {mage.core.IState} state
* @param {archivist.IArchivistIndex} index
* @param {archivist.IArchivistGetOptions} [options]
* @returns
*
* @memberof ValidatedTopic
*/
public static async get<T extends ValidatedTopic>(
this: IStaticThis<T>,
state: mage.core.IState,
index: archivist.IArchivistIndex,
options?: archivist.IArchivistGetOptions): Promise<T> {
const topicName = this.getClassName()
return this.execute<T, T>(state, 'get', [
topicName,
index,
options
], async (data: any) => {
// If optional: true, and no data was found
if (options && options.optional && !data) {
return undefined
}
return this.create(state, index, data)
})
}
/**
* Try to get a topic instance from backend vault(s)
*
* Same as `get`, but is also states that `undefined' might be returned instead.
* You should consider using this method instead of calling `get` directly
* with the `optional: true` option.
*
* @static
* @param {mage.core.IState} state
* @param {archivist.IArchivistIndex} index
* @param {archivist.IArchivistGetOptions} [options]
* @returns
*
* @memberof ValidatedTopic
*/
public static async tryGet<T extends ValidatedTopic>(
this: IStaticThis<T>,
state: mage.core.IState,
index: archivist.IArchivistIndex,
options?: archivist.IArchivistGetOptions): Promise<T | undefined> {
if (!options) {
options = {}
}
options.optional = true
return this.get(state, index, options)
}
/**
* Get instances from backend vault(s)
*
* Mostly a wrapper around state.archivist.mget.
*
* @static
* @param {mage.core.IState} state
* @param {archivist.IArchivistQuery[]} queries
* @param {archivist.IArchivistGetOptions} [options]
* @returns
*
* @memberof ValidatedTopic
*/
public static async mget<T extends ValidatedTopic>(
this: IStaticThis<T>,
state: mage.core.IState,
indexes: archivist.IArchivistIndex[],
options?: archivist.IArchivistGetOptions): Promise<T[]> {
const topic = this.getClassName()
const queries: archivist.IArchivistQuery[] = indexes.map((index) => ({ topic, index }))
return this.execute<T, T[]>(state, 'mget', [
queries,
options
], async (list: any) => {
const instances: ValidatedTopic[] = []
for (let d = 0; d < list.length; d += 1) {
const data = list[d]
const index = queries[d].index
const instance = await this.create(state, index, data)
instances.push(instance)
}
return instances
})
}
//
// Todo:
//
// public static async mget(state: mage.core.IState, queries: archivist.INamedArchivistQuery, options?: archivist.IArchivistGetOptions) {
// return new Promise((resolve, reject) => {
// state.archivist.mget(queries, options, async (error, list) => {
// if (error) {
// return reject(error)
// }
// const instances = Object.keys(list).reduce((instances, name) => {
// if (list[name]) {
// instances[name] = this.create(state, queries[name], list[name])
// }
// return instances
// }, {})
// resolve(instances)
// })
// })
// }
/**
* List all keys
*
* @static
* @param {mage.core.IState} state
* @param {archivist.IArchivistIndex} partialIndex
* @param {archivist.IArchivistGetOptions} [options]
* @returns
*
* @memberof ValidatedTopic
*/
public static async list<T extends ValidatedTopic>(
this: IStaticThis<T>,
state: mage.core.IState, partialIndex:
archivist.IArchivistIndex,
options?: archivist.IArchivistListOptions): Promise<archivist.IArchivistIndex[]> {
const topicName = this.getClassName()
return this.execute<T, archivist.IArchivistIndex[]>(state, 'list', [
topicName,
partialIndex,
options,
], (indexes: archivist.IArchivistIndex[]) => indexes)
}
/**
* Query data by partial index
*
* Essentially wraps state.archivist.list, then fetches the data
* for each keys using state.archivist.mget.
*
* @static
* @param {mage.core.IState} state
* @param {archivist.IArchivistIndex} partialIndex
* @param {archivist.IArchivistGetOptions} [options]
* @returns
*
* @memberof ValidatedTopic
*/
public static async query<T extends ValidatedTopic>(
this: IStaticThis<T>,
state: mage.core.IState,
partialIndex: archivist.IArchivistIndex,
options?: archivist.IArchivistGetOptions): Promise<T[]> {
const topicName = this.getClassName()
return this.execute<T, T[]>(state, 'list', [
topicName,
partialIndex
], async (indexes: archivist.IArchivistIndex[]) => {
return this.mget<T>(state, indexes, options)
})
}
/**
* Creates an instance of ValidatedTopic.
*
* @param {mage.core.IState} state
*
* @memberof ValidatedTopic
*/
constructor(state?: mage.core.IState) {
this.setTopic(this.constructor.name)
if (state) {
this.setState(state)
}
}
/**
* Get the topic for this instance
*
* @memberof ValidatedTopic
*/
public getTopic() {
return <string> (<any> this)._topic
}
/**
* Set the topic name for this instance
*
* @param {string} topicName
*
* @memberof ValidatedTopic
*/
public setTopic(topicName: string) {
Object.defineProperty(this, '_topic', {
value: topicName,
configurable: true
})
}
/**
* Get the topic of that instance
*
* Should always return the class name of the instance.
*
* @returns
*
* @memberof ValidatedTopic
*/
public getIndex() {
return <archivist.IArchivistIndex> (<any> this)._index
}
/**
* Set the index of this topic instance
*
* @param {archivist.IArchivistIndex} index
*
* @memberof ValidatedTopic
*/
public async setIndex(indexData: archivist.IArchivistIndex) {
const Class: any = this.constructor
const Index = Class.indexType
const index = new Index()
for (const field of Class.index) {
index[field] = indexData[field]
}
await classValidator.validate(index).then((errors) => throwOnError('Invalid index', errors))
Object.defineProperty(this, '_index', {
value: index,
configurable: true
})
}
/**
* Retrieve the state object attached to the instance
*
* @returns
*
* @memberof ValidatedTopic
*/
public getState() {
return <mage.core.IState> (<any> this)._state
}
/**
* Set the state this topic instance will be using.
*
* @param {mage.core.IState} state
*
* @memberof ValidatedTopic
*/
public setState(state: mage.core.IState) {
Object.defineProperty(this, '_state', {
value: state,
configurable: true
})
}
/**
* Retrieve the actual data for this instance
*
* This should essentially be the same as simply accessing data on the
* instance itself.
*
* @returns
*
* @memberof ValidatedTopic
*/
public getData() {
return this
}
/**
* Record an add operation on the instance's state
*
* Essentially a wrapper for state.archivist.add
*
* @param {archivist.ArchivistMediaType} mediaType
* @param {archivist.ArchivistEncoding} encoding
* @param {number} [expirationTime]
* @returns
*
* @memberof ValidatedTopic
*/
public async add(mediaType?: archivist.ArchivistMediaType, encoding?: archivist.ArchivistEncoding, expirationTime?: number) {
await this.validate()
return this.getState().archivist.add(this.getTopic(), this.getIndex(), this.getData(), mediaType, encoding, expirationTime)
}
/**
* Record a set operation on the instance's state
*
* Essentially a wrapper for state.archivist.set.
*
* @param {archivist.ArchivistMediaType} mediaType
* @param {archivist.ArchivistEncoding} encoding
* @param {number} [expirationTime]
* @returns
*
* @memberof ValidatedTopic
*/
public async set(mediaType?: archivist.ArchivistMediaType, encoding?: archivist.ArchivistEncoding, expirationTime?: number) {
await this.validate()
return this.getState().archivist.set(this.getTopic(), this.getIndex(), this.getData(), mediaType, encoding, expirationTime)
}
/**
* Record a touch operation on the instance's state
*
* Essentially a wrapper for state.archivist.touch.
*
* @param {number} [expirationTime]
* @returns
*
* @memberof ValidatedTopic
*/
public async touch(expirationTime?: number) {
await this.validate()
return this.getState().archivist.touch(this.getTopic(), this.getIndex(), expirationTime)
}
/**
* Record a delete operation on the instance's state
*
* @returns
*
* @memberof ValidatedTopic
*/
public del() {
return this.getState().archivist.del(this.getTopic(), this.getIndex())
}
/**
* Validate the current instance
*
* @returns {Promise<void>}
*
* @memberof ValidatedTopic
*/
public async validate(): Promise<void> {
return classValidator.validate(this).then((errors) => throwOnError('Invalid type', errors))
}
}
/**
* Wrap tome and sub-tome instances intp proxies, allowing
* for direct access to attributes
*
* @param tome Tome instance
*/
function createTomeProxy(tome: any): any {
return new Proxy(tome, {
ownKeys(target) {
return Object.keys(target).concat([
'__dirty__',
'__root__',
'__diff__',
'__diffEnabled__',
'__version__',
'__parent__',
'__key__'
])
},
get(target: any, key: string) {
const val = target[key]
if (!val || key[0] === '_') {
return val
}
if (ObjectTome.isObjectTome(val) || ArrayTome.isArrayTome(val)) {
return createTomeProxy(target[key])
}
if (typeof val === 'function') {
return val.bind(target)
}
return val.valueOf()
},
set(target: any, key: string, value) {
target.set(key, value)
return true
},
deleteProperty(_target, key: string) {
tome.del(key)
return true
}
})
}
/**
* Wrapper for validating Tome instances
*/
export class ValidatedTome {
constructor() {
const instance = createTomeProxy(Tome.conjure(this))
return instance
}
}
/**
* Dealing with tome topics
*/
export class ValidatedTomeTopic extends ValidatedTopic {
public static readonly mediaType = 'application/x-tome'
public tome: any
public static async create<T extends ValidatedTopic>(
this: IStaticThis<T>,
state: mage.core.IState,
index: archivist.IArchivistIndex,
data?: any): Promise<T> {
const tome: any = Tome.isTome(data) ? data : Tome.conjure(data || {})
const instance = new this()
instance.setTopic(this.getClassName())
instance.setState(state)
await instance.setIndex(index)
return new Proxy(instance, {
ownKeys() {
return Object.keys(tome)
},
getOwnPropertyDescriptor(target: any, key) {
return { configurable: true, enumerable: true, value: this.get(target, key) }
},
get(target: any, key) {
/* istanbul ignore next */
if (key === 'set' || key === 'del') {
return target[key]
}
if (key === 'constructor') {
return target.constructor
}
if (key === 'tome') {
return tome
}
if (!tome[key]) {
return target[key]
}
if (ObjectTome.isObjectTome(tome[key]) || ArrayTome.isArrayTome(tome[key])) {
return createTomeProxy(tome[key])
}
return tome[key].valueOf()
},
set(_target: any, key, value) {
tome.set(key, value)
return true
},
deleteProperty(target, key) {
const val = tome[key]
if (Tome.isTome(val)) {
tome.del(key)
}
delete target[key]
return true
}
})
}
public getData() {
return this.tome
}
}
/**
* @Acl decorator
*
* Protect the user command with the given ACL and defined type validation
*
* @export
* @param {...string[]} acl
* @returns
*/
export function Acl(...acl: string[]) {
return function (UserCommand: any, key: string) {
if (key !== 'execute') {
throw crash('@validate only works for usercommand.execute functions', {
method: key,
userCommand: UserCommand
})
}
const execute = <IExecuteFunction> UserCommand.execute
const parameterNames = functionArguments(execute)
const types = Reflect.getMetadata('design:paramtypes', UserCommand, key)
// We extract the state information, since we won't need it
parameterNames.shift()
types.shift()
// We attach additional information to the UserCommand class
UserCommand.acl = acl
UserCommand.params = parameterNames
async function validateObject(message: string, obj: any) {
return classValidator.validate(obj).then((errors) => throwOnError(message, errors, obj))
}
return {
value: async (state: mage.core.IState, ...args: any[]) => {
// Map user command's parameters
const userCommandData: { [key: string]: any } = {}
args.forEach((arg, pos) => {
const parameterName = parameterNames[pos]
userCommandData[parameterName] = arg
})
// Cast data into a user command instance
const userCommand = classTransformer.plainToClass(UserCommand, userCommandData)
for (const { value } of deepIterator(userCommand)) {
if (value instanceof ValidatedTopic) {
value.setState(state)
const index = (<any> value).index || {}
await value.setIndex(index)
delete (<any> value).index
}
}
// Validate all parameters at once
await validateObject('Invalid user command input', userCommand)
// Map casted parameters into an array of arguments
const castedArgs = args.map((_arg, pos) => {
const parameterName = parameterNames[pos]
return (<any> userCommand)[parameterName]
})
// Execute the actual user command
const output = await execute(state, ...castedArgs)
// Validate the returned value
const type = typeof output
if (type !== 'object') {
return output
}
if (!Array.isArray(output)) {
return validateObject('Invalid user command return value', output)
}
// In the case of arrays, validate each entries
for (const [pos, val] of output.entries()) {
await validateObject(`Invalid user command return value in array (index: ${pos})`, val)
}
return output
}
}
}
}
|