diff options
Diffstat (limited to 'src/server/database.ts')
-rw-r--r-- | src/server/database.ts | 61 |
1 files changed, 25 insertions, 36 deletions
diff --git a/src/server/database.ts b/src/server/database.ts index 51103520e..07c5819ab 100644 --- a/src/server/database.ts +++ b/src/server/database.ts @@ -8,55 +8,53 @@ export class Database { public static Instance = new Database() private MongoClient = mongodb.MongoClient; private url = 'mongodb://localhost:27017/Dash'; + private db?: mongodb.Db; + + constructor() { + this.MongoClient.connect(this.url, (err, client) => { + this.db = client.db() + }) + } public update(id: string, value: any) { - this.MongoClient.connect(this.url, { bufferMaxEntries: 1 }, (err, db) => { - let collection = db.db().collection('documents'); + if (this.db) { + let collection = this.db.collection('documents'); collection.update({ _id: id }, { $set: value }, { upsert: true }); - db.close(); - }); + } } public delete(id: string) { - this.MongoClient.connect(this.url, { bufferMaxEntries: 1 }, (err, db) => { - let collection = db.db().collection('documents'); + if (this.db) { + let collection = this.db.collection('documents'); collection.remove({ _id: id }); - db.close(); - }); + } } public deleteAll() { - this.MongoClient.connect(this.url, (err, db) => { - let collection = db.db().collection('documents'); + if (this.db) { + let collection = this.db.collection('documents'); collection.deleteMany({}); - }) + } } public insert(kvpairs: any) { - this.MongoClient.connect(this.url, { bufferMaxEntries: 1 }, (err, db) => { - let collection = db.db().collection('documents'); + if (this.db) { + let collection = this.db.collection('documents'); collection.insertOne(kvpairs, (err: any, res: any) => { if (err) { // console.log(err) return } }); - db.close(); - }); + } } public getDocument(id: string, fn: (res: any) => void) { var result: JSON; - this.MongoClient.connect(this.url, { - bufferMaxEntries: 1 - }, (err, db) => { - if (err) { - console.log(err) - return undefined - } - let collection = db.db().collection('documents'); + if (this.db) { + let collection = this.db.collection('documents'); collection.findOne({ _id: id }, (err: any, res: any) => { result = res if (!result) { @@ -64,26 +62,17 @@ export class Database { } fn(result) }) - db.close(); - }); + }; } public getDocuments(ids: string[], fn: (res: any) => void) { - var result: JSON; - this.MongoClient.connect(this.url, { - bufferMaxEntries: 1 - }, (err, db) => { - if (err) { - console.log(err) - return undefined - } - let collection = db.db().collection('documents'); + if (this.db) { + let collection = this.db.collection('documents'); let cursor = collection.find({ _id: { "$in": ids } }) cursor.toArray((err, docs) => { fn(docs); }) - db.close(); - }); + }; } public print() { |