Repository navigation
Expand file tree
/
Copy pathDocumentContext.ts
More file actions
97 lines (80 loc) · 2.5 KB
/
Copy pathDocumentContext.ts
File metadata and controls
97 lines (80 loc) · 2.5 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
import PouchDB from 'pouchdb'
import { Merge } from '@nnode/core'
import { Lincoln } from '@nnode/lincoln'
import { DocumentStore } from './DocumentStore'
import { CouchConfig } from './config/CouchConfig'
export abstract class DocumentContext<T extends CouchConfig> {
private readonly log: Lincoln
protected readonly store: DocumentStore
constructor(public readonly config: T, logger: Lincoln) {
this.log = logger.extend('document-context')
this.store = new DocumentStore(config, this.log)
this.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,
}
this.log.debug('sync-live', config.name, options)
return this.store.sync(remote, options).on('change', (change) => this.log.trace(change))
// .on('error', (error) => this.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)
this.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>
}