-
-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy pathindex.ts
1031 lines (894 loc) · 27.6 KB
/
index.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
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
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import Change from './-private/change';
import { getKeyValues, getKeyErrorValues } from './utils/get-key-values';
import lookupValidator from './utils/validator-lookup';
import { notifierForEvent } from './-private/evented';
import Err from './-private/err';
import normalizeObject from './utils/normalize-object';
import pureAssign from './utils/assign';
import { flattenValidations } from './utils/flatten-validations';
import isChangeset, { CHANGESET } from './utils/is-changeset';
import isObject from './utils/is-object';
import { isLeafInChanges } from './utils/is-leaf';
import isPromise from './utils/is-promise';
import keyInObject from './utils/key-in-object';
import mergeNested from './utils/merge-nested';
import objectWithout from './utils/object-without';
import take from './utils/take';
import mergeDeep from './utils/merge-deep';
import setDeep from './utils/set-deep';
import getDeep from './utils/get-deep';
import {
Changes,
Config,
Content,
Errors,
IErr,
IChangeset,
INotifier,
InternalMap,
NewProperty,
PrepareChangesFn,
RunningValidations,
Snapshot,
ValidationErr,
ValidationResult,
ValidatorAction,
ValidatorMap
} from './types';
export {
CHANGESET,
Change,
Err,
isChangeset,
isObject,
isPromise,
getKeyValues,
keyInObject,
lookupValidator,
mergeNested,
normalizeObject,
objectWithout,
pureAssign,
take,
mergeDeep,
setDeep,
getDeep
};
const { keys } = Object;
const CONTENT = '_content';
const CHANGES = '_changes';
const ERRORS = '_errors';
const VALIDATOR = '_validator';
const OPTIONS = '_options';
const RUNNING_VALIDATIONS = '_runningValidations';
const BEFORE_VALIDATION_EVENT = 'beforeValidation';
const AFTER_VALIDATION_EVENT = 'afterValidation';
const AFTER_ROLLBACK_EVENT = 'afterRollback';
const defaultValidatorFn = () => true;
const defaultOptions = { skipValidate: false };
const DEBUG = process.env.NODE_ENV !== 'production';
function assert(msg: string, property: unknown): void {
if (DEBUG) {
if (!property) {
throw new Error(msg);
}
}
}
export class BufferedChangeset implements IChangeset {
constructor(
obj: object,
public validateFn: ValidatorAction = defaultValidatorFn,
public validationMap: ValidatorMap = {},
options: Config = {}
) {
this[CONTENT] = obj;
this[CHANGES] = {};
this[ERRORS] = {};
this[VALIDATOR] = validateFn;
this[OPTIONS] = pureAssign(defaultOptions, options);
this[RUNNING_VALIDATIONS] = {};
}
/**
* Any property that is not one of the getter/setter/methods on the
* BufferedProxy instance. The value type is `unknown` in order to avoid
* having to predefine key/value pairs of the correct types in the target
* object. Setting the index signature to `[key: string]: T[K]` would allow us
* to typecheck the value that is set on the proxy. However, no
* getters/setters/methods can be added to the class. This is the tradeoff
* we make for this particular design pattern (class based BufferedProxy).
*/
[key: string]: unknown;
[CONTENT]: object;
[CHANGES]: Changes;
[ERRORS]: Errors<any>;
[VALIDATOR]: ValidatorAction;
[OPTIONS]: {};
[RUNNING_VALIDATIONS]: {};
__changeset__ = CHANGESET;
_eventedNotifiers = {};
on(eventName: string, callback: Function): INotifier {
const notifier = notifierForEvent(this, eventName);
return notifier.addListener(callback);
}
off(eventName: string, callback: Function): INotifier {
const notifier = notifierForEvent(this, eventName);
return notifier.removeListener(callback);
}
trigger(eventName: string, ...args: any[]): void {
const notifier = notifierForEvent(this, eventName);
if (notifier) {
notifier.trigger(...args);
}
}
/**
* @property setDeep
* @override
*/
setDeep = setDeep;
/**
* @property getDeep
* @override
*/
getDeep = getDeep;
/**
* @property safeGet
* @override
*/
safeGet(obj: any, key: string) {
return obj[key];
}
get _bareChanges() {
function transform(c: Change) {
return c.value;
}
let obj = this[CHANGES];
return keys(obj).reduce((newObj: { [key: string]: any }, key: string) => {
newObj[key] = transform(obj[key]);
return newObj;
}, Object.create(null));
}
/**
* @property changes
* @type {Array}
*/
get changes() {
let obj = this[CHANGES];
// [{ key, value }, ...]
return getKeyValues(obj);
}
/**
* @property errors
* @type {Array}
*/
get errors() {
let obj = this[ERRORS];
// [{ key, validation, value }, ...]
return getKeyErrorValues(obj);
}
get change() {
let obj: Changes = this[CHANGES];
return normalizeObject(obj);
}
get error() {
return this[ERRORS];
}
get data() {
return this[CONTENT];
}
/**
* @property isValid
* @type {Array}
*/
get isValid() {
return getKeyValues(this[ERRORS]).length === 0;
}
/**
* @property isPristine
* @type {Boolean}
*/
get isPristine() {
return Object.keys(this[CHANGES]).length === 0;
}
/**
* @property isInvalid
* @type {Boolean}
*/
get isInvalid() {
return !this.isValid;
}
/**
* @property isDirty
* @type {Boolean}
*/
get isDirty() {
return !this.isPristine;
}
/**
* Stores change on the changeset.
* This approximately works just like the Ember API
*
* @method setUnknownProperty
*/
setUnknownProperty<T>(key: string, value: T): void {
let config: Config = this[OPTIONS];
let skipValidate: boolean | undefined = config['skipValidate'];
let content: Content = this[CONTENT];
let oldValue = this.safeGet(content, key);
if (skipValidate) {
this._setProperty({ key, value, oldValue });
this._handleValidation(true, { key, value });
return;
}
this._setProperty({ key, value, oldValue });
this._validateKey(key, value);
}
/**
* String representation for the changeset.
*/
toString(): string {
let normalisedContent: object = pureAssign(this[CONTENT], {});
return `changeset:${normalisedContent.toString()}`;
}
/**
* Provides a function to run before emitting changes to the model. The
* callback function must return a hash in the same shape:
*
* ```
* changeset
* .prepare((changes) => {
* let modified = {};
*
* for (let key in changes) {
* modified[underscore(key)] = changes[key];
* }
*
* return modified; // { first_name: "Jim", last_name: "Bob" }
* })
* .execute(); // execute the changes
* ```
*
* @method prepare
*/
prepare(prepareChangesFn: PrepareChangesFn): this {
let changes: { [s: string]: any } = this._bareChanges;
let preparedChanges = prepareChangesFn(changes);
assert('Callback to `changeset.prepare` must return an object', isObject(preparedChanges));
let newObj: Changes = {};
if (isObject(preparedChanges)) {
let newChanges: Changes = keys(preparedChanges as Record<string, any>).reduce(
(newObj: Changes, key: keyof Changes) => {
newObj[key] = new Change((preparedChanges as Record<string, any>)[key]);
return newObj;
},
newObj
);
// @tracked
this[CHANGES] = newChanges;
}
return this;
}
/**
* Executes the changeset if in a valid state.
*
* @method execute
*/
execute(): this {
if (this.isValid && this.isDirty) {
let content: Content = this[CONTENT];
let changes: Changes = this[CHANGES];
// we want mutation on original object
// @tracked
this[CONTENT] = mergeDeep(content, changes);
}
// trigger any registered callbacks by same keyword as method name
this.trigger('execute');
return this;
}
/**
* Executes the changeset and saves the underlying content.
*
* @method save
* @param {Object} options optional object to pass to content save method
*/
async save(options?: object): Promise<IChangeset | any> {
let content: Content = this[CONTENT];
let savePromise: any | Promise<BufferedChangeset | any> = Promise.resolve(this);
this.execute();
if (typeof content.save === 'function') {
savePromise = content.save(options);
} else if (typeof this.safeGet(content, 'save') === 'function') {
// we might be getting this off a proxy object. For example, when a
// belongsTo relationship (a proxy on the parent model)
// another way would be content(belongsTo).content.save
let saveFunc: Function = this.safeGet(content, 'save');
if (saveFunc) {
savePromise = saveFunc(options);
}
}
const result = await savePromise;
this.rollback();
return result;
}
/**
* Merges 2 valid changesets and returns a new changeset. Both changesets
* must point to the same underlying object. The changeset target is the
* origin. For example:
*
* ```
* let changesetA = new Changeset(user, validatorFn);
* let changesetB = new Changeset(user, validatorFn);
* changesetA.set('firstName', 'Jim');
* changesetB.set('firstName', 'Jimmy');
* changesetB.set('lastName', 'Fallon');
* let changesetC = changesetA.merge(changesetB);
* changesetC.execute();
* user.get('firstName'); // "Jimmy"
* user.get('lastName'); // "Fallon"
* ```
*
* @method merge
*/
merge(changeset: this): this {
let content: Content = this[CONTENT];
assert('Cannot merge with a non-changeset', isChangeset(changeset));
assert('Cannot merge with a changeset of different content', changeset[CONTENT] === content);
if (this.isPristine && changeset.isPristine) {
return this;
}
let c1: Changes = this[CHANGES];
let c2: Changes = changeset[CHANGES];
let e1: Errors<any> = this[ERRORS];
let e2: Errors<any> = changeset[ERRORS];
// eslint-disable-next-line @typescript-eslint/no-use-before-define
let newChangeset: any = new ValidatedChangeset(content, this[VALIDATOR]); // ChangesetDef
let newErrors: Errors<any> = objectWithout(keys(c2), e1);
let newChanges: Changes = objectWithout(keys(e2), c1);
let mergedErrors: Errors<any> = mergeNested(newErrors, e2);
let mergedChanges: Changes = mergeNested(newChanges, c2);
newChangeset[ERRORS] = mergedErrors;
newChangeset[CHANGES] = mergedChanges;
newChangeset._notifyVirtualProperties();
return newChangeset;
}
/**
* Returns the changeset to its pristine state, and discards changes and
* errors.
*
* @method rollback
*/
rollback(): this {
// Get keys before reset.
let keys = this._rollbackKeys();
// Reset.
this[CHANGES] = {};
this[ERRORS] = {};
this._notifyVirtualProperties(keys);
this.trigger(AFTER_ROLLBACK_EVENT);
return this;
}
/**
* Discards any errors, keeping only valid changes.
*
* @public
* @chainable
* @method rollbackInvalid
* @param {String} key optional key to rollback invalid values
* @return {Changeset}
*/
rollbackInvalid(key: string | void): this {
let errorKeys = keys(this[ERRORS]);
if (key) {
this._notifyVirtualProperties([key]);
// @tracked
this[ERRORS] = this._deleteKey(ERRORS, key) as Errors<any>;
if (errorKeys.indexOf(key) > -1) {
this[CHANGES] = this._deleteKey(CHANGES, key) as Changes;
}
} else {
this._notifyVirtualProperties();
this[ERRORS] = {};
// if on CHANGES hash, rollback those as well
errorKeys.forEach(errKey => {
this[CHANGES] = this._deleteKey(CHANGES, errKey) as Changes;
});
}
return this;
}
/**
* Discards changes/errors for the specified properly only.
*
* @public
* @chainable
* @method rollbackProperty
* @param {String} key key to delete off of changes and errors
* @return {Changeset}
*/
rollbackProperty(key: string): this {
// @tracked
this[CHANGES] = this._deleteKey(CHANGES, key) as Changes;
// @tracked
this[ERRORS] = this._deleteKey(ERRORS, key) as Errors<any>;
return this;
}
/**
* Validates the changeset immediately against the validationMap passed in.
* If no key is passed into this method, it will validate all fields on the
* validationMap and set errors accordingly. Will throw an error if no
* validationMap is present.
*
* @method validate
*/
validate(...validationKeys: string[]): Promise<any> {
if (keys(this.validationMap as object).length === 0 && !validationKeys.length) {
return Promise.resolve(null);
}
validationKeys =
validationKeys.length > 0
? validationKeys
: keys(flattenValidations(this.validationMap as object));
let maybePromise = validationKeys.map(key => {
const x = this._validateKey(key as string, this._valueFor(key as string));
return x;
});
return Promise.all(maybePromise);
}
/**
* Manually add an error to the changeset. If there is an existing
* error or change for `key`, it will be overwritten.
*
* @method addError
*/
addError<T>(key: string, error: IErr<T> | ValidationErr) {
// Construct new `Err` instance.
let newError;
const isIErr = <T>(error: unknown): error is IErr<T> =>
isObject(error) && !Array.isArray(error);
if (isIErr(error)) {
assert('Error must have value.', error.hasOwnProperty('value') || error.value !== undefined);
assert('Error must have validation.', error.hasOwnProperty('validation'));
newError = new Err(error.value, error.validation);
} else {
let value = this[key];
newError = new Err(value, error as ValidationErr);
}
// Add `key` to errors map.
let errors: Errors<any> = this[ERRORS];
// @tracked
this[ERRORS] = this.setDeep(errors, key, newError, { safeSet: this.safeSet });
// Return passed-in `error`.
return error;
}
/**
* Manually push multiple errors to the changeset as an array.
* key maybe in form 'name.short' so need to go deep
*
* @method pushErrors
*/
pushErrors(key: string, ...newErrors: string[] | ValidationErr[]): IErr<any> {
let errors: Errors<any> = this[ERRORS];
let existingError: IErr<any> | Err = this.getDeep(errors, key) || new Err(null, []);
let validation: ValidationErr | ValidationErr[] = existingError.validation;
let value: any = this[key];
if (!Array.isArray(validation) && Boolean(validation)) {
existingError.validation = [validation];
}
let v = existingError.validation;
validation = [...v, ...newErrors];
let newError = new Err(value, validation);
// @tracked
this[ERRORS] = this.setDeep(errors, key as string, newError, { safeSet: this.safeSet });
return { value, validation };
}
/**
* Creates a snapshot of the changeset's errors and changes.
*
* @method snapshot
*/
snapshot(): Snapshot {
let changes: Changes = this[CHANGES];
let errors: Errors<any> = this[ERRORS];
return {
changes: keys(changes).reduce((newObj: Changes, key: keyof Changes) => {
newObj[key] = changes[key].value;
return newObj;
}, {}),
errors: keys(errors).reduce((newObj: Errors<any>, key: keyof Errors<any>) => {
let e = errors[key];
newObj[key] = { value: e.value, validation: e.validation };
return newObj;
}, {})
};
}
/**
* Restores a snapshot of changes and errors. This overrides existing
* changes and errors.
*
* @method restore
*/
restore({ changes, errors }: Snapshot): this {
let newChanges: Changes = keys(changes).reduce((newObj: Changes, key: keyof Changes) => {
newObj[key] = new Change(changes[key]);
return newObj;
}, {});
let newErrors: Errors<any> = keys(errors).reduce((newObj: Errors<any>, key: keyof Changes) => {
let e: IErr<any> = errors[key];
newObj[key] = new Err(e.value, e.validation);
return newObj;
}, {});
// @tracked
this[CHANGES] = newChanges;
// @tracked
this[ERRORS] = newErrors;
this._notifyVirtualProperties();
return this;
}
/**
* Unlike `Ecto.Changeset.cast`, `cast` will take allowed keys and
* remove unwanted keys off of the changeset. For example, this method
* can be used to only allow specified changes through prior to saving.
*
* @method cast
*/
cast(allowed: string[] = []): this {
let changes: Changes = this[CHANGES];
if (Array.isArray(allowed) && allowed.length === 0) {
return this;
}
let changeKeys: string[] = keys(changes);
let validKeys = changeKeys.filter((key: string) => allowed.includes(key));
let casted = take(changes, validKeys);
// @tracked
this[CHANGES] = casted;
return this;
}
/**
* Checks to see if async validator for a given key has not resolved.
* If no key is provided it will check to see if any async validator is running.
*
* @method isValidating
*/
isValidating(key?: string | void): boolean {
let runningValidations: RunningValidations = this[RUNNING_VALIDATIONS];
let ks: string[] = keys(runningValidations);
if (key) {
return ks.includes(key);
}
return ks.length > 0;
}
/**
* Validates a specific key
*
* @method _validateKey
* @private
*/
_validateKey<T>(
key: string,
value: T
): Promise<ValidationResult | T | IErr<T>> | T | IErr<T> | ValidationResult {
let content: Content = this[CONTENT];
let oldValue: any = this.getDeep(content, key);
let validation: ValidationResult | Promise<ValidationResult> = this._validate(
key,
value,
oldValue
);
this.trigger(BEFORE_VALIDATION_EVENT, key);
// TODO: Address case when Promise is rejected.
if (isPromise(validation)) {
this._setIsValidating(key, true);
return (validation as Promise<ValidationResult>)
.then((resolvedValidation: ValidationResult) => {
this._setIsValidating(key, false);
return this._handleValidation(resolvedValidation, { key, value });
})
.then(result => {
this.trigger(AFTER_VALIDATION_EVENT, key);
return result;
});
}
let result = this._handleValidation(validation as ValidationResult, { key, value });
this.trigger(AFTER_VALIDATION_EVENT, key);
return result;
}
/**
* Takes resolved validation and adds an error or simply returns the value
*
* @method _handleValidation
* @private
*/
_handleValidation<T>(
validation: ValidationResult,
{ key, value }: NewProperty<T>
): T | IErr<T> | ValidationErr {
const isValid: boolean =
validation === true ||
(Array.isArray(validation) && validation.length === 1 && validation[0] === true);
// Happy path: remove `key` from error map.
// @tracked
this[ERRORS] = this._deleteKey(ERRORS, key) as Errors<any>;
// Error case.
if (!isValid) {
return this.addError(key, { value, validation } as IErr<T>);
}
return value;
}
/**
* runs the validator with the key and value
*
* @method _validate
* @private
*/
_validate(
key: string,
newValue: unknown,
oldValue: unknown
): ValidationResult | Promise<ValidationResult> {
let validator: ValidatorAction = this[VALIDATOR];
let content: Content = this[CONTENT];
if (typeof validator === 'function') {
let isValid = validator({
key,
newValue,
oldValue,
changes: this.change,
content
});
return typeof isValid === 'boolean' || Boolean(isValid) ? isValid : true;
}
return true;
}
/**
* Sets property or error on the changeset.
* Returns value or error
*/
_setProperty<T>({ key, value, oldValue }: NewProperty<T>): void {
let changes: Changes = this[CHANGES];
// Happy path: update change map.
if (oldValue !== value) {
// @tracked
const result = this.setDeep(changes, key, new Change(value), { safeSet: this.safeSet });
this[CHANGES] = result;
} else if (keyInObject(changes, key)) {
// @tracked
this[CHANGES] = this._deleteKey(CHANGES, key) as Changes;
}
}
/**
* Increment or decrement the number of running validations for a
* given key.
*/
_setIsValidating(key: string, value: boolean): void {
let running: RunningValidations = this[RUNNING_VALIDATIONS];
let count: number = running[key] || 0;
if (!value && count === 1) {
delete running[key];
return;
}
this.setDeep(running, key, value ? count + 1 : count - 1);
}
/**
* Value for change/error/content or the original value.
*/
_valueFor(key: string): any {
let changes: Changes = this[CHANGES];
let errors: Errors<any> = this[ERRORS];
let content: Content = this[CONTENT];
if (errors.hasOwnProperty(key)) {
let e: Err = errors[key];
return e.value;
}
// 'person'
if (Object.prototype.hasOwnProperty.apply(changes, [key])) {
let result: Change = changes[key];
if (isObject(result)) {
return normalizeObject(result);
}
return result.value;
}
// 'person.username'
let [baseKey, ...remaining] = key.split('.');
if (Object.prototype.hasOwnProperty.apply(changes, [baseKey])) {
let c: Change = changes[baseKey];
let result = this.getDeep(normalizeObject(c), remaining.join('.'));
// just b/c top level key exists doesn't mean it has the nested key we are looking for
if (typeof result !== 'undefined') {
return result;
}
}
let original: any = this.getDeep(content, key);
return original;
}
/**
* Notifies virtual properties set on the changeset of a change.
* You can specify which keys are notified by passing in an array.
*
* @private
* @param {Array} keys
* @return {Void}
*/
_notifyVirtualProperties(keys?: string[]): string[] | undefined {
if (!keys) {
keys = this._rollbackKeys();
}
return keys;
}
/**
* Gets the changes and error keys.
*/
_rollbackKeys(): string[] {
let changes: Changes = this[CHANGES];
let errors: Errors<any> = this[ERRORS];
return [...new Set([...keys(changes), ...keys(errors)])];
}
/**
* Deletes a key off an object and notifies observers.
*/
_deleteKey(objName: string, key = ''): InternalMap {
let obj = this[objName] as InternalMap;
let keys = key.split('.');
if (keys.length === 1 && obj.hasOwnProperty(key)) {
delete obj[key];
} else if (obj[keys[0]]) {
let [base, ...remaining] = keys;
let previousNode: { [key: string]: any } = obj;
let currentNode: any = obj[base];
let currentKey: string | undefined = base;
// find leaf and delete from map
while (isObject(currentNode) && currentKey) {
let curr: { [key: string]: unknown } = currentNode;
if (typeof curr.value !== 'undefined' || curr.validation) {
delete previousNode[currentKey];
}
currentKey = remaining.shift();
previousNode = currentNode;
if (currentKey) {
currentNode = currentNode[currentKey];
}
}
}
return obj;
}
get(key: string): any {
// 'person'
// 'person.username'
let [baseKey, ...remaining] = key.split('.');
if (Object.prototype.hasOwnProperty.call(this[CHANGES], baseKey)) {
let changes: Changes = this[CHANGES];
let result: Record<string, any>;
if (remaining.length > 0) {
let c = changes[baseKey];
result = this.getDeep(normalizeObject(c), remaining.join('.'));
if (typeof result !== 'undefined') {
return result;
}
} else {
result = changes[baseKey];
}
if (result !== undefined && result !== null && isObject(result)) {
// 1. Knock out any class Change{} instances
result = normalizeObject(result);
// 2. then ensure sibling keys are merged with the "result"
let content: Content = this[CONTENT];
// Merge the content with the changes to have a complete object for a nested property.
// Given a object with nested property and multiple properties inside of it, if the
// requested key is the top most nested property and we have changes in of the properties, we need to
// merge the original model data with the changes to have the complete object.
// eg. model = { user: { name: 'not changed', email: '[email protected]'} }
if (
!Array.isArray(result) &&
isObject(content[baseKey]) &&
!isLeafInChanges(key, changes)
) {
let netKeys = Object.keys(content[baseKey]);
if (netKeys.length === 0) {
return result;
}
// 3. Ok merge sibling keys. Yes, shallow clone, but users should treat `c.get` as read only. Mods to data
// structures should happen through `c.set(...)` or `{{changeset-set ...}}`
const data = Object.assign(
Object.create(Object.getPrototypeOf(content[baseKey])),
result
);
netKeys.forEach(k => {
const inResult = this.safeGet(result, k);
const contentData = this.getDeep(content, `${baseKey}.${k}`);
if (
isObject(inResult) &&
isObject(contentData) &&
contentData.constructor.name === 'Object'
) {
data[k] = { ...contentData, ...inResult };
} else if (!inResult) {
data[k] = contentData;
}
});
return data;
}
return result;
}
if (result) {
return result.value;
}
}
// return getters/setters/methods on BufferedProxy instance
if (typeof this[key] !== 'undefined') {
return this[key];
} else if (typeof this[baseKey] !== 'undefined') {
const v: unknown = this[baseKey];
if (isObject(v)) {
const result = this.getDeep(v as Record<string, any>, remaining.join('.'));
return result;
}
}
// finally return on underlying object
let content: Content = this[CONTENT];
const result = this.getDeep(content, key);
return result;
}
set<T>(
key: string,
value: T
): void | Promise<ValidationResult | T | IErr<T>> | T | IErr<T> | ValidationResult {
if (this.hasOwnProperty(key) || keyInObject(this, key)) {
this[key] = value;
return;
}
this.setUnknownProperty(key, value);
}
}
/**
* Creates new changesets.
*/
export function changeset(
obj: object,
validateFn?: ValidatorAction,
validationMap?: ValidatorMap | null | undefined,
options?: Config
): BufferedChangeset {
return new BufferedChangeset(obj, validateFn, validationMap, options);
}
type T20 = InstanceType<typeof BufferedChangeset>;
export class ValidatedChangeset {
/**
* Changeset factory class if you need to extend
*
* @class ValidatedChangeset
* @constructor
*/
constructor(
obj: object,
validateFn?: ValidatorAction,
validationMap?: ValidatorMap | null | undefined,
options?: Config
) {
const c: BufferedChangeset = changeset(obj, validateFn, validationMap, options);
return new Proxy(c, {
get(targetBuffer, key /*, receiver*/) {
const res = targetBuffer.get(key.toString());