Skip to content

Commit

Permalink
Merge branch 'batchwrite' into main
Browse files Browse the repository at this point in the history
  • Loading branch information
abkarino committed Oct 13, 2022
2 parents cd35906 + c7199b4 commit 31a2dbb
Showing 1 changed file with 16 additions and 9 deletions.
25 changes: 16 additions & 9 deletions WriteBatch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,15 @@
* Can be atomic or not.
*/
class WriteBatch {
private mutations_: FirestoreAPI.Write[] = [];
private committed_ = false;
#mutations: FirestoreAPI.Write[] = [];
#committed = false;

/**
* Getter to check if a WriteBatch has pending write
*/
public get isEmpty() {
return this.#mutations.length === 0;
}

/**
* A container for multiple writes
Expand Down Expand Up @@ -52,7 +59,7 @@ class WriteBatch {
updateMask: updateMask,
update: update,
};
this.mutations_.push(mutation);
this.#mutations.push(mutation);
return this;
}

Expand Down Expand Up @@ -111,7 +118,7 @@ class WriteBatch {
exists: true,
},
};
this.mutations_.push(mutation);
this.#mutations.push(mutation);
return this;
}

Expand All @@ -128,7 +135,7 @@ class WriteBatch {
const mutation: FirestoreAPI.Write = {
delete: `${this._firestore.basePath}${path}`,
};
this.mutations_.push(mutation);
this.#mutations.push(mutation);
return this;
}

Expand All @@ -139,23 +146,23 @@ class WriteBatch {
*/
commit(atomic = false): boolean | Array<true | string | undefined> {
this.verifyNotCommitted_();
this.committed_ = true;
if (!this.mutations_.length) {
this.#committed = true;
if (!this.#mutations.length) {
throw new Error('A write batch cannot commit with no changes requested.');
}

const request = new Request(this._firestore.baseUrl, this._firestore.authToken);
request.route(atomic ? 'commit' : 'batchWrite');

const payload: FirestoreAPI.CommitRequest | FirestoreAPI.BatchWriteRequest = { writes: this.mutations_ };
const payload: FirestoreAPI.CommitRequest | FirestoreAPI.BatchWriteRequest = { writes: this.#mutations };
const responseObj = request.post<FirestoreAPI.CommitResponse | FirestoreAPI.BatchWriteResponse>(undefined, payload);

if (atomic) return true;
else return ((responseObj as FirestoreAPI.BatchWriteResponse).status || []).map((s) => !s.code || s.message);
}

private verifyNotCommitted_(): void {
if (this.committed_) {
if (this.#committed) {
throw new Error('A write batch can no longer be used after commit() ' + 'has been called.');
}
}
Expand Down

0 comments on commit 31a2dbb

Please sign in to comment.