Skip to content

Commit

Permalink
fix: Handle errors thrown from updates.
Browse files Browse the repository at this point in the history
  • Loading branch information
jwalton committed Aug 16, 2021
1 parent 395a9b5 commit 8a928f0
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 12 deletions.
32 changes: 20 additions & 12 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,10 @@ export class ImmutableModelStore<S> {
this.current = produce(initialState, () => void 0) as Immutable<S>;
}

public get updating(): boolean {
return !!this._isUpdating;
}

/**
* update() will synchronously update the state of the model.
*
Expand All @@ -35,22 +39,26 @@ export class ImmutableModelStore<S> {
} else {
const draft = (this._isUpdating = createDraft(this.current) as Draft<S>);

// Apply the update...
const voidResult = fn(draft) as any;
try {
// Apply the update...
const voidResult = fn(draft) as any;

// Paranoid check for async functions...
if (typeof voidResult === 'object' && 'then' in voidResult) {
throw new Error('Updates must be synchronous');
}
// Paranoid check for async functions...
if (typeof voidResult === 'object' && 'then' in voidResult) {
throw new Error('Updates must be synchronous');
}

const newState = finishDraft(draft) as Immutable<S>;
const newState = finishDraft(draft) as Immutable<S>;

this._isUpdating = undefined;
if (newState !== this.current) {
this.current = newState;
this._isUpdating = undefined;
if (newState !== this.current) {
this.current = newState;

// Notify subscribers.
this._subscribers.forEach((subscriber) => subscriber(this.current));
// Notify subscribers.
this._subscribers.forEach((subscriber) => subscriber(this.current));
}
} finally {
this._isUpdating = undefined;
}
}
}
Expand Down
17 changes: 17 additions & 0 deletions test/ImmutableModelStoreTest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,4 +83,21 @@ describe('ImmutableModelStore', () => {
});
expect(listener).to.have.beenCalledTimes(1);
});

it('should handle an exception from update', () => {
const store = new ImmutableModelStore({ name: 'Jason', age: 30 });

expect(() =>
store.update((state) => {
state.age = 31;
throw new Error('boom');
})
).to.throw('boom');

// Update should not have been applied.
expect(store.current.age).to.equal(30);

// We should not be in the middle of a re-rentrant update.
expect(store.updating).to.be.false;
});
});

0 comments on commit 8a928f0

Please sign in to comment.