Skip to content

Commit

Permalink
Fix restore method to work with nested keys (#160)
Browse files Browse the repository at this point in the history
* Fix restore method to work with nested changes object

* Insert missed semicolons
  • Loading branch information
linainu authored Feb 15, 2022
1 parent e38b508 commit 7b77cfa
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 4 deletions.
23 changes: 19 additions & 4 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -686,10 +686,7 @@ export class BufferedChangeset implements IChangeset {
* @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 newChanges: Changes = this.getChangesFromSnapshot(changes);

let newErrors: Errors<any> = keys(errors).reduce((newObj: Errors<any>, key: keyof Changes) => {
let e: IErr<any> = errors[key];
Expand All @@ -707,6 +704,24 @@ export class BufferedChangeset implements IChangeset {
return this;
}

private getChangesFromSnapshot(changes: Changes) {
return keys(changes).reduce((newObj, key) => {
newObj[key] = this.getChangeForProp(changes[key]);
return newObj;
}, {} as Changes);
}

private getChangeForProp(value: any) {
if (!isObject(value)) {
return new Change(value);
}

return keys(value).reduce((newObj, key) => {
newObj[key] = this.getChangeForProp(value[key]);
return newObj;
}, {} as Changes);
}

/**
* Unlike `Ecto.Changeset.cast`, `cast` will take allowed keys and
* remove unwanted keys off of the changeset. For example, this method
Expand Down
4 changes: 4 additions & 0 deletions test/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3223,6 +3223,10 @@ describe('Unit | Utility | changeset', () => {

expect(changeset.get('name')).toBe('Jim Bob');
expect(changeset.get('address.country')).toBe('North Korea');
expect(changeset.changes).toEqual([
{ key: 'name', value: 'Jim Bob' },
{ key: 'address.country', value: 'North Korea' }
]);
});

/**
Expand Down

0 comments on commit 7b77cfa

Please sign in to comment.