Repository navigation
Expand file tree
/
Copy pathBUCollectionManager.ts
More file actions
92 lines (72 loc) · 2.69 KB
/
Copy pathBUCollectionManager.ts
File metadata and controls
92 lines (72 loc) · 2.69 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
//Includes
import { BUError } from './BUError'
import { BUCollection } from './BUCollection'
import { BUDocument } from './BUDocument'
export class BUCollectionManager {
timer: any
//Singleton
private static _instance: BUCollectionManager
public static get instance(){ return this._instance || (this._instance = new this()) }
private constructor(){ this.uploadAllPerform() }
//Store collections
collections: { [key: string]: BUCollection } = {}
//Upload timer interval
interval = 2000.0
//Events
error: (collection: BUCollection, error: BUError) => void
success: (collection: BUCollection, uploaded: number) => void
//Create collections from array of name
create(names: string[]){
for (const name of names){
//Check name doesn't exists in collections
if (Object.keys(this.collections).includes(name)){
continue
}
//Create new collection if name doesnt exist
this.collections[name] = new BUCollection(name)
}
}
//Convenience method for adding a document to a collection and creating the collection if non-existant
push(collection: string, document: BUDocument | Object){
//Create document if object given
let data
if (document instanceof Object){
document = new BUDocument(data)
}else{
data = document
}
//Check whether document exists and create
if (!Object.keys(this.collections).includes(name)){
this.collections[collection] = new BUCollection(collection)
}
//Add document to collection
this.collections[collection].push(data)
}
//Push documents in all collections to backend server
private uploadAllPerform(timer?: any){
this.uploadAll()
//Create timer to push all collections every x seconds
if (this.interval > 0){
setTimeout(() => {
this.uploadAllPerform()
}, this.interval)
}
}
uploadAll(){
//Push all collections
Object.keys(this.collections).forEach(key => {
const collection = this.collections[key]
collection.upload((code: BUError) => {
//Notify error
if (this.error !== undefined){
this.error(collection, code)
}
}, (count: number) => {
//Notify success
if (this.success !== undefined){
this.success(collection, count)
}
})
})
}
}