diff options
author | Tyler Schicke <tyler_schicke@brown.edu> | 2019-05-06 15:17:59 -0400 |
---|---|---|
committer | Tyler Schicke <tyler_schicke@brown.edu> | 2019-05-06 15:17:59 -0400 |
commit | d6919d0779df080990c52157540564af95c98a18 (patch) | |
tree | 46c827719ab961b0b1eafbae796c3bc1be1d8106 | |
parent | a9f465a32ac538c8dcf94bd37afda730e7be3526 (diff) |
Added synchronization to db insert
-rw-r--r-- | src/server/database.ts | 25 |
1 files changed, 17 insertions, 8 deletions
diff --git a/src/server/database.ts b/src/server/database.ts index 37cfcf3a3..69005d2d3 100644 --- a/src/server/database.ts +++ b/src/server/database.ts @@ -22,13 +22,6 @@ export class Database { return new Promise<void>(resolve => { collection.updateOne({ _id: id }, value, { upsert } , (err, res) => { - if (err) { - console.log(err.message); - console.log(err.errmsg); - } - // if (res) { - // console.log(JSON.stringify(res.result)); - // } if (this.currentWrites[id] === newProm) { delete this.currentWrites[id]; } @@ -52,11 +45,27 @@ export class Database { } public insert(value: any, collectionName = Database.DocumentsCollection) { + if (!this.db) { return; } if ("id" in value) { value._id = value.id; delete value.id; } - this.db && this.db.collection(collectionName).insertOne(value); + const id = value._id; + const collection = this.db.collection(collectionName); + const prom = this.currentWrites[id]; + let newProm: Promise<void>; + const run = (): Promise<void> => { + return new Promise<void>(resolve => { + collection.insertOne(value, (err, res) => { + if (this.currentWrites[id] === newProm) { + delete this.currentWrites[id]; + } + resolve(); + }); + }); + }; + newProm = prom ? prom.then(run) : run(); + this.currentWrites[id] = newProm; } public getDocument(id: string, fn: (result?: Transferable) => void, collectionName = Database.DocumentsCollection) { |