Repository navigation
Expand file tree
/
Copy pathDocumentContext.ts
More file actions
98 lines (80 loc) · 2.39 KB
/
Copy pathDocumentContext.ts
File metadata and controls
98 lines (80 loc) · 2.39 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
93
94
95
96
97
98
import PouchDB from 'pouchdb'
import { Logger, Merge } from '@sosus/core'
import { DocumentStore } from './DocumentStore'
import { CouchConfig } from './config/CouchConfig'
const log = Logger.extend('document-context')
export abstract class DocumentContext<T extends CouchConfig> {
protected readonly store: DocumentStore
constructor(public readonly config: T) {
this.store = new DocumentStore(config)
log.debug('create-document-context', config)
}
get name() {
return this.config.name
}
from(config: CouchConfig) {
const remote = new PouchDB(config.name, config)
return new Promise((resolve, reject) => {
this.store.replicate.from(remote, {}, (error, results) => {
if (error) {
reject(error)
} else {
resolve(results)
}
})
})
}
live(config: CouchConfig): PouchDB.Replication.Sync<{}> {
const remote = new PouchDB(config.name, config)
const options: PouchDB.Replication.SyncOptions = {
pull: {
retry: true,
live: true,
},
push: undefined,
}
log.debug('sync-live', config.name, options)
return this.store
.sync(remote, options)
.on('change', change => log.trace(change))
.on('error', error => log.error(error))
}
async sync(config: CouchConfig, options?: PouchDB.Replication.SyncOptions) {
const opts = Merge([{ retry: true }, options || {}])
return new Promise<PouchDB.Replication.SyncResultComplete<{}> | null>((resolve, reject) => {
const remote = new PouchDB(config.name, config)
log.debug('sync-context', config)
this.store.sync(remote, opts, (error, results) => {
if (error) {
reject(error)
} else {
resolve(results)
}
})
})
}
to(config: CouchConfig) {
const remote = new PouchDB(config.name, config)
return new Promise((resolve, reject) => {
this.store.replicate.to(remote, {}, (error, results) => {
if (error) {
reject(error)
} else {
resolve(results)
}
})
})
}
async initialize() {
if (['http', undefined].includes(this.config.adapter)) {
await this.store.createIndex({
index: {
fields: ['meta__doctype'],
name: 'meta__doctype',
},
})
await this.createIndexDocuments()
}
}
protected abstract createIndexDocuments(): Promise<void>
}