smartdata/ts/smartdata.classes.dbcollection.ts

61 lines
1.8 KiB
TypeScript
Raw Normal View History

2016-09-11 16:01:46 +00:00
import * as plugins from './smartdata.plugins'
import { DbConnection } from './smartdata.classes.dbconnection'
export class DbCollection<T> {
collection: plugins.mongodb.Collection
constructor(nameArg: string, dbConnectionArg: DbConnection) {
this.collection = dbConnectionArg.db.collection(nameArg)
}
/**
* adds a validation function that all newly inserted and updated objects have to pass
*/
2016-09-12 16:14:01 +00:00
addObjectValidation(funcArg) { }
2016-09-11 16:01:46 +00:00
/**
2016-09-12 15:31:23 +00:00
* finds an object in the DbCollection
2016-09-11 16:01:46 +00:00
*/
2016-09-12 16:14:01 +00:00
find(docMatchArg: T): plugins.q.Promise<T[]> {
let done = plugins.q.defer<T[]>()
2016-09-12 19:36:26 +00:00
this.collection.find(docMatchArg).toArray((err, docs) => {
2016-09-12 16:14:01 +00:00
if (err) { throw err }
done.resolve(docs)
})
return done.promise
2016-09-12 15:31:23 +00:00
}
/**
* inserts object into the DbCollection
*/
2016-09-12 16:14:01 +00:00
insertOne(docArg: T): plugins.q.Promise<void> {
let done = plugins.q.defer<void>()
this.checkDoc(docArg).then(() => {
this.collection.insertOne(docArg)
.then(() => { done.resolve() })
})
return done.promise
2016-09-12 15:31:23 +00:00
}
2016-09-11 16:01:46 +00:00
/**
* inserts many objects at once into the DbCollection
*/
2016-09-12 16:14:01 +00:00
insertMany(docArrayArg: T[]): plugins.q.Promise<void> {
let done = plugins.q.defer<void>()
let checkDocPromiseArray: plugins.q.Promise<void>[] = []
for (let docArg of docArrayArg){
checkDocPromiseArray.push(this.checkDoc(docArg))
}
plugins.q.all(checkDocPromiseArray).then(() => {
this.collection.insertMany(docArrayArg)
2016-09-12 19:36:26 +00:00
.then(() => { done.resolve() })
2016-09-12 16:14:01 +00:00
})
return done.promise
}
2016-09-12 15:31:23 +00:00
2016-09-12 16:14:01 +00:00
private checkDoc(doc: T): plugins.q.Promise<void> {
let done = plugins.q.defer<void>()
done.resolve()
return done.promise
2016-09-12 15:31:23 +00:00
}
2016-09-11 16:01:46 +00:00
}