2016-09-13 20:53:21 +00:00
|
|
|
import * as plugins from './smartdata.plugins'
|
|
|
|
|
|
|
|
import { Db } from './smartdata.classes.db'
|
|
|
|
import { DbCollection } from './smartdata.classes.dbcollection'
|
|
|
|
|
2016-11-17 23:59:57 +00:00
|
|
|
export type TDocCreation = 'db' | 'new' | 'mixed'
|
2016-09-13 20:53:21 +00:00
|
|
|
|
2016-11-17 23:42:25 +00:00
|
|
|
/**
|
2016-11-17 23:59:57 +00:00
|
|
|
* saveable - saveable decorator to be used on class properties
|
2016-11-17 23:42:25 +00:00
|
|
|
*/
|
|
|
|
export function saveable(target: DbDoc<any>, key: string) {
|
|
|
|
console.log('called sva')
|
|
|
|
if (!target.saveableProperties) { target.saveableProperties = [] }
|
|
|
|
target.saveableProperties.push(key)
|
|
|
|
}
|
2016-09-13 23:02:11 +00:00
|
|
|
|
2016-09-13 20:53:21 +00:00
|
|
|
export class DbDoc<T> {
|
2016-11-17 23:42:25 +00:00
|
|
|
|
|
|
|
/**
|
|
|
|
* the collection object an Doc belongs to
|
|
|
|
*/
|
2016-09-13 20:53:21 +00:00
|
|
|
collection: DbCollection<T>
|
2016-11-17 23:42:25 +00:00
|
|
|
|
|
|
|
/**
|
|
|
|
* how the Doc in memory was created, may prove useful later.
|
|
|
|
*/
|
2016-09-13 20:53:21 +00:00
|
|
|
creationType: TDocCreation
|
2016-11-17 23:42:25 +00:00
|
|
|
|
|
|
|
/**
|
|
|
|
* an array of saveable properties of a doc
|
|
|
|
*/
|
|
|
|
saveableProperties: string[]
|
|
|
|
|
|
|
|
/**
|
|
|
|
* class constructor
|
|
|
|
*/
|
2016-09-13 23:02:11 +00:00
|
|
|
constructor() {
|
|
|
|
this.collection = this.constructor['dbCollection']
|
2016-09-13 20:53:21 +00:00
|
|
|
}
|
2016-11-17 23:42:25 +00:00
|
|
|
|
|
|
|
/**
|
|
|
|
* saves this instance but not any connected items
|
|
|
|
* may lead to data inconsistencies, but is faster
|
|
|
|
*/
|
2016-09-13 20:53:21 +00:00
|
|
|
save() {
|
2016-11-17 23:42:25 +00:00
|
|
|
let saveableObject = {}
|
|
|
|
for (let propertyNameString of this.saveableProperties) {
|
|
|
|
saveableObject[propertyNameString] = this[propertyNameString]
|
|
|
|
}
|
2016-11-17 23:59:57 +00:00
|
|
|
switch (this.creationType) {
|
|
|
|
case 'db':
|
|
|
|
this.collection // TODO implement collection.update()
|
|
|
|
break
|
|
|
|
case 'new':
|
|
|
|
this.collection.insertOne(saveableObject)
|
|
|
|
}
|
2016-09-13 20:53:21 +00:00
|
|
|
}
|
2016-09-13 23:02:11 +00:00
|
|
|
|
2016-11-17 23:42:25 +00:00
|
|
|
/**
|
|
|
|
* also store any referenced objects to DB
|
|
|
|
* better for data consistency
|
|
|
|
*/
|
|
|
|
saveDeep() {
|
|
|
|
this.save()
|
2016-09-13 20:53:21 +00:00
|
|
|
}
|
|
|
|
}
|