Skip to content

Commit b4be171

Browse files
committed
Flush batch only after "commit" is called
Store batch operations in a gueue before execution. This will prevent documents from being created/updated/deleted before `batch.commit()` is even called. This issue was especially annoying when autoFlush is enabled.
1 parent 241af33 commit b4be171

File tree

2 files changed

+54
-9
lines changed

2 files changed

+54
-9
lines changed

src/firestore.js

Lines changed: 26 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -69,25 +69,42 @@ MockFirestore.prototype.runTransaction = function(transFunc) {
6969
});
7070
};
7171

72+
var processBatchQueue = function (queue) {
73+
_.forEach(queue, function (queueItem) {
74+
var method = queueItem.method;
75+
var doc = queueItem.args[0];
76+
var data = queueItem.args[1];
77+
var opts = queueItem.args[2];
78+
79+
if (method === 'set') {
80+
if (opts && opts.merge === true) {
81+
doc._update(data, { setMerge: true });
82+
} else {
83+
doc.set(data);
84+
}
85+
} else if (method === 'update') {
86+
doc.update(data);
87+
} else if (method === 'delete') {
88+
doc.delete();
89+
}
90+
});
91+
}
92+
7293
MockFirestore.prototype.batch = function () {
7394
var self = this;
95+
var queue = [];
7496
return {
7597
set: function(doc, data, opts) {
76-
var _opts = _.assign({}, { merge: false }, opts);
77-
if (_opts.merge) {
78-
doc._update(data, { setMerge: true });
79-
}
80-
else {
81-
doc.set(data);
82-
}
98+
queue.push({ method: 'set', args: [doc, data, opts] });
8399
},
84100
update: function(doc, data) {
85-
doc.update(data);
101+
queue.push({ method: 'update', args: [doc, data] });
86102
},
87103
delete: function(doc) {
88-
doc.delete();
104+
queue.push({ method: 'delete', args: [doc] });
89105
},
90106
commit: function() {
107+
processBatchQueue(queue);
91108
if (self.queue.events.length > 0) {
92109
self.flush();
93110
}

test/unit/firestore.js

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -185,5 +185,33 @@ describe('MockFirestore', function () {
185185

186186
db.flush();
187187
});
188+
189+
context('when "batch.commit" is not called', function () {
190+
afterEach(function () {
191+
db.doc('col/batch-foo').delete();
192+
db.doc('col/batch-bar').delete();
193+
db.flush();
194+
});
195+
196+
it('does not create documents', function (done) {
197+
var batch = db.batch();
198+
batch.set(db.doc('col/batch-foo'), { foo: 'fooo' });
199+
batch.set(db.doc('col/batch-bar'), { bar: 'barr' });
200+
201+
expect(function () { db.flush() }).to.throw(Error)
202+
203+
var promises = [
204+
db.doc('col/batch-foo').get(),
205+
db.doc('col/batch-bar').get()
206+
]
207+
db.flush()
208+
209+
Promise.all(promises).then(function (docs) {
210+
expect(docs[0].exists).to.eq(false);
211+
expect(docs[1].exists).to.eq(false);
212+
done();
213+
});
214+
});
215+
});
188216
});
189217
});

0 commit comments

Comments
 (0)