Created
May 1, 2017 17:13
-
-
Save ajaxray/0881ffe1faed0618976c674d4661e021 to your computer and use it in GitHub Desktop.
Simplest (just connect, create, find, count) MongoDB wrapper.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import {Query} from './query' | |
let MongoClient = require('mongodb').MongoClient; | |
let defaultFailure = function (err) { throw err; }; | |
class Mongo { | |
connected: boolean; | |
db: any; | |
constructor(public url: string) { | |
this.connected = false; | |
} | |
connect (withDb?: Function) { | |
if(! this.connected) { | |
MongoClient.connect(this.url, (err, db) => { | |
if(err) throw err; | |
this.db = db; | |
this.connected = true; | |
if(withDb) withDb(this.db) | |
}) | |
} else { | |
withDb(this.db) | |
} | |
return this; | |
} | |
disconnect() { | |
this.db.close(); | |
this.connected = false; | |
} | |
insert(collName: string, document: any, onSuccess: Function, onFailure?: Function) { | |
let failure = onFailure || defaultFailure; | |
this.connect(db => { | |
db.collection(collName).insertOne(document, (err, result) => { | |
// Result - http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#~insertOneWriteOpResult | |
err && failure(err) || onSuccess(result); | |
}) | |
}) | |
}; | |
findAll(collName: string, query: Query, withResult: Function) { | |
this.connect(db => { | |
let collection = db.collection(collName); | |
let condition = query.condition || {}; | |
let cursor = collection.find(condition); | |
if(query.order) cursor.sort(query.order); | |
if(query.limit) cursor.limit(query.limit); | |
if(query.offset) cursor.skip(query.offset); | |
cursor.toArray((err, result) => { | |
err && defaultFailure(err) || withResult(result); | |
}) | |
}) | |
} | |
count(collName: string, query: Query, withResult: Function) { | |
this.connect(db => { | |
let collection = db.collection(collName); | |
let condition = query.condition || {}; | |
collection.count(condition).then(total => withResult(total)); | |
}) | |
} | |
} | |
module.exports = Mongo; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export interface Query { | |
condition?: Object, | |
order?: Object, | |
limit?: number | |
offset?: number | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment