Skip to content

Commit a53489c

Browse files
authored
Merge pull request #668 from streamich/fix-nested-transactions
Allow nested transactions
2 parents 5b6349a + d687561 commit a53489c

File tree

2 files changed

+39
-3
lines changed

2 files changed

+39
-3
lines changed

src/json-crdt/json-patch/__tests__/JsonPatchStore.spec.ts

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -103,3 +103,30 @@ test('can bind store to a "str" node', async () => {
103103
store2.update({op: 'str_ins', path: '', pos: 3, str: 'x'});
104104
expect(store2.getSnapshot()).toEqual('abcx');
105105
});
106+
107+
test('can execute mutations inside a transaction', async () => {
108+
const model = Model.create(
109+
s.obj({
110+
ui: s.obj({
111+
state: s.obj({
112+
text: s.str('abc'),
113+
counter: s.con(123),
114+
}),
115+
}),
116+
}),
117+
);
118+
const store = new JsonPatchStore(model, ['ui']);
119+
const store2 = store.bind('/state/text');
120+
expect(store2.getSnapshot()).toEqual('abc');
121+
let cnt = 0;
122+
model.api.onTransaction.listen(() => {
123+
cnt++;
124+
});
125+
model.api.transaction(() => {
126+
store2.update({op: 'str_ins', path: '', pos: 3, str: 'x'});
127+
});
128+
expect(cnt).toBe(1);
129+
await tick(1);
130+
expect(cnt).toBe(1);
131+
expect(store2.getSnapshot()).toEqual('abcx');
132+
});

src/json-crdt/model/api/ModelApi.ts

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -262,10 +262,19 @@ export class ModelApi<N extends JsonNode = JsonNode> implements SyncStore<JsonNo
262262
return this.model.view();
263263
}
264264

265+
private inTx = false;
265266
public transaction(callback: () => void) {
266-
this.onBeforeTransaction.emit();
267-
callback();
268-
this.onTransaction.emit();
267+
if (this.inTx) callback();
268+
else {
269+
this.inTx = true;
270+
try {
271+
this.onBeforeTransaction.emit();
272+
callback();
273+
this.onTransaction.emit();
274+
} finally {
275+
this.inTx = false;
276+
}
277+
}
269278
}
270279

271280
/**

0 commit comments

Comments
 (0)