Skip to content

Commit 6fe85a7

Browse files
committed
feat: Inject Pouch engine and local storage
1 parent 308052c commit 6fe85a7

File tree

6 files changed

+165
-88
lines changed

6 files changed

+165
-88
lines changed

packages/cozy-pouch-link/src/CozyPouchLink.js

Lines changed: 15 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -18,13 +18,8 @@ import * as jsonapi from './jsonapi'
1818
import PouchManager from './PouchManager'
1919
import logger from './logger'
2020
import { migratePouch } from './migrations/adapter'
21+
import { platformWeb } from './platformWeb'
2122
import { getDatabaseName, getPrefix } from './utils'
22-
import {
23-
getPersistedSyncedDoctypes,
24-
persistAdapterName,
25-
getAdapterName,
26-
destroyWarmedUpQueries
27-
} from './localStorage'
2823

2924
PouchDB.plugin(PouchDBFind)
3025

@@ -95,6 +90,7 @@ class PouchLink extends CozyLink {
9590
this.doctypes = doctypes
9691
this.doctypesReplicationOptions = doctypesReplicationOptions
9792
this.indexes = {}
93+
this.storage = options.platform?.storage || platformWeb.storage
9894

9995
/** @type {Record<string, SyncStatus>} - Stores replication states per doctype */
10096
this.replicationStatus = this.replicationStatus || {}
@@ -149,15 +145,15 @@ class PouchLink extends CozyLink {
149145
for (const plugin of plugins) {
150146
PouchDB.plugin(plugin)
151147
}
152-
const doctypes = getPersistedSyncedDoctypes()
148+
const doctypes = await this.storage.getPersistedSyncedDoctypes()
153149
for (const doctype of Object.keys(doctypes)) {
154150
const prefix = getPrefix(url)
155151
const dbName = getDatabaseName(prefix, doctype)
156152

157153
await migratePouch({ dbName, fromAdapter, toAdapter })
158-
destroyWarmedUpQueries() // force recomputing indexes
154+
await this.storage.destroyWarmedUpQueries() // force recomputing indexes
159155
}
160-
persistAdapterName('indexeddb')
156+
await this.storage.persistAdapterName('indexeddb')
161157
} catch (err) {
162158
console.error('PouchLink: PouchDB migration failed. ', err)
163159
}
@@ -195,9 +191,9 @@ class PouchLink extends CozyLink {
195191
logger.log('Create pouches with ' + prefix + ' prefix')
196192
}
197193

198-
if (!getAdapterName()) {
194+
if (!(await this.storage.getAdapterName())) {
199195
const adapter = get(this.options, 'pouch.options.adapter')
200-
persistAdapterName(adapter)
196+
await this.storage.persistAdapterName(adapter)
201197
}
202198

203199
this.pouches = new PouchManager(this.doctypes, {
@@ -209,8 +205,10 @@ class PouchLink extends CozyLink {
209205
onDoctypeSyncStart: this.handleDoctypeSyncStart.bind(this),
210206
onDoctypeSyncEnd: this.handleDoctypeSyncEnd.bind(this),
211207
prefix,
212-
executeQuery: this.executeQuery.bind(this)
208+
executeQuery: this.executeQuery.bind(this),
209+
platform: this.options.platform
213210
})
211+
await this.pouches.init()
214212

215213
if (this.client && this.options.initialSync) {
216214
this.startReplication()
@@ -334,7 +332,7 @@ class PouchLink extends CozyLink {
334332
return !!this.getPouch(impactedDoctype)
335333
}
336334

337-
request(operation, result = null, forward = doNothing) {
335+
async request(operation, result = null, forward = doNothing) {
338336
const doctype = getDoctypeFromOperation(operation)
339337

340338
if (!this.pouches) {
@@ -387,18 +385,18 @@ class PouchLink extends CozyLink {
387385
* and return if those queries are already warmed up or not
388386
*
389387
* @param {string} doctype - Doctype to check
390-
* @returns {boolean} the need to wait for the warmup
388+
* @returns {Promise<boolean>} the need to wait for the warmup
391389
*/
392-
needsToWaitWarmup(doctype) {
390+
async needsToWaitWarmup(doctype) {
393391
if (
394392
this.doctypesReplicationOptions &&
395393
this.doctypesReplicationOptions[doctype] &&
396394
this.doctypesReplicationOptions[doctype].warmupQueries
397395
) {
398-
return !this.pouches.areQueriesWarmedUp(
396+
return !(await this.pouches.areQueriesWarmedUp(
399397
doctype,
400398
this.doctypesReplicationOptions[doctype].warmupQueries
401-
)
399+
))
402400
}
403401
return false
404402
}

packages/cozy-pouch-link/src/PouchManager.js

Lines changed: 43 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
import PouchDB from 'pouchdb-browser'
21
import fromPairs from 'lodash/fromPairs'
32
import forEach from 'lodash/forEach'
43
import get from 'lodash/get'
@@ -10,9 +9,9 @@ import { QueryDefinition } from 'cozy-client'
109

1110
import Loop from './loop'
1211
import logger from './logger'
12+
import { platformWeb } from './platformWeb'
1313
import { fetchRemoteLastSequence } from './remote'
1414
import { startReplication } from './startReplication'
15-
import * as localStorage from './localStorage'
1615
import { getDatabaseName } from './utils'
1716

1817
const DEFAULT_DELAY = 30 * 1000
@@ -35,20 +34,33 @@ const getQueryAlias = query => {
3534
class PouchManager {
3635
constructor(doctypes, options) {
3736
this.options = options
38-
const pouchPlugins = get(options, 'pouch.plugins', [])
39-
const pouchOptions = get(options, 'pouch.options', {})
37+
this.doctypes = doctypes
4038

41-
forEach(pouchPlugins, plugin => PouchDB.plugin(plugin))
39+
/**
40+
* @type {import("./types").PouchLocalStorage}
41+
*/
42+
this.storage = options.platform?.storage || platformWeb.storage
43+
this.PouchDB = options.platform?.pouchEngine || platformWeb.pouchEngine
44+
}
45+
46+
async init() {
47+
const pouchPlugins = get(this.options, 'pouch.plugins', [])
48+
const pouchOptions = get(this.options, 'pouch.options', {})
49+
50+
forEach(pouchPlugins, plugin => this.PouchDB.plugin(plugin))
4251
this.pouches = fromPairs(
43-
doctypes.map(doctype => [
52+
this.doctypes.map(doctype => [
4453
doctype,
45-
new PouchDB(getDatabaseName(options.prefix, doctype), pouchOptions)
54+
new this.PouchDB(
55+
getDatabaseName(this.options.prefix, doctype),
56+
pouchOptions
57+
)
4658
])
4759
)
48-
this.syncedDoctypes = localStorage.getPersistedSyncedDoctypes()
49-
this.warmedUpQueries = localStorage.getPersistedWarmedUpQueries()
50-
this.getReplicationURL = options.getReplicationURL
51-
this.doctypesReplicationOptions = options.doctypesReplicationOptions || {}
60+
this.syncedDoctypes = await this.storage.getPersistedSyncedDoctypes()
61+
this.warmedUpQueries = await this.storage.getPersistedWarmedUpQueries()
62+
this.getReplicationURL = this.options.getReplicationURL
63+
this.doctypesReplicationOptions = this.options.doctypesReplicationOptions || {}
5264
this.listenerLaunched = false
5365

5466
// We must ensure databases exist on the remote before
@@ -85,13 +97,13 @@ class PouchManager {
8597
}
8698
}
8799

88-
destroy() {
100+
async destroy() {
89101
this.stopReplicationLoop()
90102
this.removeListeners()
91-
this.clearSyncedDoctypes()
92-
this.clearWarmedUpQueries()
93-
localStorage.destroyAllDoctypeLastSequence()
94-
localStorage.destroyAllLastReplicatedDocID()
103+
await this.clearSyncedDoctypes()
104+
await this.clearWarmedUpQueries()
105+
await this.storage.destroyAllDoctypeLastSequence()
106+
await this.storage.destroyAllLastReplicatedDocID()
95107

96108
return Promise.all(
97109
Object.values(this.pouches).map(pouch => pouch.destroy())
@@ -182,9 +194,9 @@ class PouchManager {
182194
// Before the first replication, get the last remote sequence,
183195
// which will be used as a checkpoint for the next replication
184196
const lastSeq = await fetchRemoteLastSequence(getReplicationURL())
185-
localStorage.persistDoctypeLastSequence(doctype, lastSeq)
197+
await this.storage.persistDoctypeLastSequence(doctype, lastSeq)
186198
} else {
187-
seq = localStorage.getDoctypeLastSequence(doctype)
199+
seq = await this.storage.getDoctypeLastSequence(doctype)
188200
}
189201

190202
const replicationOptions = get(
@@ -203,15 +215,16 @@ class PouchManager {
203215
const res = await startReplication(
204216
pouch,
205217
replicationOptions,
206-
getReplicationURL
218+
getReplicationURL,
219+
this.storage
207220
)
208221
if (seq) {
209222
// We only need the sequence for the second replication, as PouchDB
210223
// will use a local checkpoint for the next runs.
211-
localStorage.destroyDoctypeLastSequence(doctype)
224+
await this.storage.destroyDoctypeLastSequence(doctype)
212225
}
213226

214-
this.updateSyncInfo(doctype)
227+
await this.updateSyncInfo(doctype)
215228
this.checkToWarmupDoctype(doctype, replicationOptions)
216229
if (this.options.onDoctypeSyncEnd) {
217230
this.options.onDoctypeSyncEnd(doctype)
@@ -273,9 +286,9 @@ class PouchManager {
273286
return this.pouches[doctype]
274287
}
275288

276-
updateSyncInfo(doctype) {
289+
async updateSyncInfo(doctype) {
277290
this.syncedDoctypes[doctype] = { date: new Date().toISOString() }
278-
localStorage.persistSyncedDoctypes(this.syncedDoctypes)
291+
await this.storage.persistSyncedDoctypes(this.syncedDoctypes)
279292
}
280293

281294
getSyncInfo(doctype) {
@@ -287,9 +300,9 @@ class PouchManager {
287300
return info ? !!info.date : false
288301
}
289302

290-
clearSyncedDoctypes() {
303+
async clearSyncedDoctypes() {
291304
this.syncedDoctypes = {}
292-
localStorage.destroySyncedDoctypes()
305+
await this.storage.destroySyncedDoctypes()
293306
}
294307

295308
async warmupQueries(doctype, queries) {
@@ -304,7 +317,7 @@ class PouchManager {
304317
}
305318
})
306319
)
307-
localStorage.persistWarmedUpQueries(this.warmedUpQueries)
320+
await this.storage.persistWarmedUpQueries(this.warmedUpQueries)
308321
logger.log('PouchManager: warmupQueries for ' + doctype + ' are done')
309322
} catch (err) {
310323
logger.error(
@@ -324,18 +337,18 @@ class PouchManager {
324337
}
325338
}
326339

327-
areQueriesWarmedUp(doctype, queries) {
328-
const persistWarmedUpQueries = localStorage.getPersistedWarmedUpQueries()
340+
async areQueriesWarmedUp(doctype, queries) {
341+
const persistWarmedUpQueries = await this.storage.getPersistedWarmedUpQueries()
329342
return queries.every(
330343
query =>
331344
persistWarmedUpQueries[doctype] &&
332345
persistWarmedUpQueries[doctype].includes(getQueryAlias(query))
333346
)
334347
}
335348

336-
clearWarmedUpQueries() {
349+
async clearWarmedUpQueries() {
337350
this.warmedUpQueries = {}
338-
localStorage.destroyWarmedUpQueries()
351+
await this.storage.destroyWarmedUpQueries()
339352
}
340353
}
341354

0 commit comments

Comments
 (0)