Skip to content

Commit

Permalink
accept version number rollover
Browse files Browse the repository at this point in the history
  • Loading branch information
Chris Nelson committed Aug 29, 2023
1 parent ba547e4 commit 413afef
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 1 deletion.
6 changes: 5 additions & 1 deletion src/LiveState.ts
Original file line number Diff line number Diff line change
Expand Up @@ -168,7 +168,7 @@ export class LiveState implements EventTarget {
this.eventTarget.dispatchEvent(new CustomEvent<LiveStatePatch>('livestate-patch', {
detail: {patch, version}
}));
if (version === this.stateVersion + 1) {
if (this.versionMatches(version)) {
const { doc, res } = applyPatch(this.state, patch, { mutate: false });
this.state = doc;
this.stateVersion = version;
Expand All @@ -183,6 +183,10 @@ export class LiveState implements EventTarget {
}
}

versionMatches(version) {
return (version === this.stateVersion + 1) || (version === 0);
}

pushEvent(eventName, payload) {
this.dispatchEvent(new CustomEvent(eventName, {detail: payload}));
}
Expand Down
27 changes: 27 additions & 0 deletions test/live-state-test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,33 @@ describe('LiveState', () => {
expect(state).to.deep.equal(newState);
});

it('accepts version number rollover in json patch', () => {
const initialState = { foo: "bar" };
const newState = { foo: "baz"};
const patch = compare(initialState, newState);
socketMock.expects('connect').exactly(1);
liveState.connect();
let state = {};
let receivedPatch;

liveState.addEventListener('livestate-change', ({detail: {state: newState}}) => state = newState);
liveState.addEventListener('livestate-patch', ({detail: {patch: thePatch}}) => receivedPatch = thePatch);

const onChangeArgs = liveState.channel.on.getCall(0).args;
expect(onChangeArgs[0]).to.equal("state:change");
const onChangeHandler = onChangeArgs[1];
onChangeHandler({state: initialState, version: 1000});

const onPatchArgs = liveState.channel.on.getCall(1).args;
expect(onPatchArgs[0]).to.equal("state:patch");
const onPatchHandler = onPatchArgs[1];
onPatchHandler({patch, version: 0});

expect(receivedPatch).to.equal(patch);
expect(state).to.deep.equal(newState);

})

it('requests new state when receiving patch with incorrect version', () => {
const initialState = { foo: "bar" };
const newState = { foo: "baz", bing: [1, 2] };
Expand Down

0 comments on commit 413afef

Please sign in to comment.