@routier/pouchdb-plugin 0.0.1-alpha.2 → 0.0.1-alpha.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,457 +1,329 @@
1
- import PouchDB from 'pouchdb';
2
- import { PouchDbTranslator } from './PouchDbTranslator';
3
- import { SyncronousQueue, SyncronousUnitOfWork, WorkPipeline } from '@routier/core/pipeline';
4
- import { InferCreateType, InferType, PropertyInfo, SchemaId } from '@routier/core/schema';
5
- import { DbPluginBulkPersistEvent, DbPluginEvent, DbPluginQueryEvent, EntityUpdateInfo, IDbPlugin, IQuery } from '@routier/core/plugins';
6
- import { CallbackResult, PluginEventCallbackPartialResult, PluginEventCallbackResult, PluginEventResult, Result } from '@routier/core/results';
7
- import { assertIsNotNull } from '@routier/core/assertions';
8
- import { combineExpressions, ComparatorExpression, Expression, getProperties } from '@routier/core/expressions';
9
- import { BulkPersistChanges, BulkPersistResult, SchemaCollection, UnknownRecord } from '@routier/core';
10
-
11
- const queue = new SyncronousQueue();
12
- const INDEX_NAME = "routier_pdb_indexes"
13
- const cache: Record<string, unknown> = {};
14
-
15
- type PouchDBPluginOptions = PouchDB.Configuration.DatabaseConfiguration & {
16
- queryType?: "default" | "memory-optimized" | "experimental";
17
- sync?: PouchDB.Replication.SyncOptions & {
18
- remoteDb: string;
19
- onChange?: (schemas: SchemaCollection, change: PouchDB.Replication.SyncResult<{}>) => void;
20
- onError?: (error: any) => void;
21
- onComplete?: (info: PouchDB.Replication.SyncResult<{}>) => void;
22
- onPaused?: (info: PouchDB.Replication.SyncResult<{}>) => void;
23
- onActive?: (info: PouchDB.Replication.SyncResult<{}>) => void;
24
- onDenied?: (info: PouchDB.Replication.SyncResult<{}>) => void;
25
- auth?: {
26
- username: string;
27
- password: string;
28
- };
29
- headers?: { [key: string]: string };
30
- };
31
- }
32
-
33
- export type PouchDbDesignDoc = {
34
- _id: string;
35
- language?: string;
36
- views?: {
37
- [viewName: string]: {
38
- map: string | Function;
39
- reduce?: string | Function;
40
- };
41
- };
42
- filters?: {
43
- [filterName: string]: string | Function;
44
- };
45
- validate_doc_update?: string | Function;
46
- options?: Record<string, any>;
47
- [key: string]: any; // allow other CouchDB features
48
- }
49
-
50
- type MatchingIndex = {
51
- viewName: string,
52
- properties: {
53
- property: PropertyInfo<any>,
54
- value: unknown
55
- }[]
56
- }
57
-
58
- export class PouchDbPlugin implements IDbPlugin {
59
-
60
- private readonly _name: string;
61
- private readonly _options?: PouchDBPluginOptions;
62
-
63
- constructor(name: string, options?: PouchDBPluginOptions) {
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.PouchDbPlugin = void 0;
7
+ const pouchdb_1 = __importDefault(require("pouchdb"));
8
+ const PouchDbTranslator_1 = require("./PouchDbTranslator");
9
+ const pipeline_1 = require("@routier/core/pipeline");
10
+ const results_1 = require("@routier/core/results");
11
+ const assertions_1 = require("@routier/core/assertions");
12
+ const expressions_1 = require("@routier/core/expressions");
13
+ const queue = new pipeline_1.SyncronousQueue();
14
+ const INDEX_NAME = "routier_pdb_indexes";
15
+ const cache = {};
16
+ class PouchDbPlugin {
17
+ _name;
18
+ _options;
19
+ constructor(name, options) {
64
20
  this._name = name;
65
21
  this._options = options;
66
22
  }
67
-
68
- private _tryStartSync(schemas: SchemaCollection) {
69
- if (this._options?.sync != null) {
70
-
71
- if (cache["sync"] == null) {
72
- cache["sync"] = {}; // placeholder
73
- const localDb = new PouchDB(this._name);
74
- const remoteDb = new PouchDB(this._options.sync.remoteDb);
75
-
76
- // Set up sync
77
- const sync = localDb.sync(remoteDb, {
78
- ...this._options.sync
79
- });
80
-
81
- sync.on('change', (change) => this._options.sync.onChange(schemas, change));
82
-
83
- cache["sync"] = sync;
23
+ sync(schemas) {
24
+ (0, assertions_1.assertIsNotNull)(this._options?.sync, "Cannot start sync process without sync options. Provide sync options in PouchDbPlugin constructor");
25
+ if (cache["sync"] == null) {
26
+ cache["sync"] = {}; // placeholder
27
+ const localDb = new pouchdb_1.default(this._name);
28
+ const remoteDb = new pouchdb_1.default(this._options.sync.remoteDb);
29
+ // Set up sync
30
+ const sync = localDb.sync(remoteDb, {
31
+ ...this._options.sync
32
+ });
33
+ if (this._options.sync.onChange) {
34
+ sync.on('change', (e) => this._options.sync.onChange(schemas, e));
35
+ }
36
+ if (this._options.sync.onActive) {
37
+ sync.on('active', () => this._options.sync.onActive(schemas));
38
+ }
39
+ if (this._options.sync.onComplete) {
40
+ sync.on('complete', (e) => this._options.sync.onComplete(schemas, e));
84
41
  }
42
+ if (this._options.sync.onDenied) {
43
+ sync.on('denied', (e) => this._options.sync.onDenied(schemas, e));
44
+ }
45
+ if (this._options.sync.onError) {
46
+ sync.on('error', (e) => this._options.sync.onError(schemas, e));
47
+ }
48
+ if (this._options.sync.onPaused) {
49
+ sync.on('paused', (e) => this._options.sync.onPaused(schemas, e));
50
+ }
51
+ cache["sync"] = sync;
85
52
  }
53
+ return cache["sync"];
86
54
  }
87
-
88
- private _identityBulkOperations(identitySchemaIds: SchemaId[], changes: BulkPersistChanges, result: BulkPersistResult, done: CallbackResult<never>): void {
89
-
55
+ _identityBulkOperations(identitySchemaIds, changes, result, done) {
90
56
  if (changes.aggregate.size === 0) {
91
- done(Result.success())
57
+ done(results_1.Result.success());
92
58
  return;
93
59
  }
94
-
95
60
  // Link each entity to a schema id below so we can easily look up the schema id for an entity
96
- const updates: { change: EntityUpdateInfo<UnknownRecord>, schemaId: SchemaId }[] = [];
97
- const adds: { entity: InferCreateType<UnknownRecord>, schemaId: SchemaId }[] = [];
98
- const removes: { entity: InferType<UnknownRecord>, schemaId: SchemaId }[] = [];
99
-
61
+ const updates = [];
62
+ const adds = [];
63
+ const removes = [];
100
64
  for (const [schemaId, schemaChanges] of changes) {
101
-
102
65
  if (identitySchemaIds.includes(schemaId) === false || schemaChanges.hasItems === false) {
103
66
  continue;
104
67
  }
105
-
106
68
  updates.push(...schemaChanges.updates.map(x => ({ change: x, schemaId })));
107
69
  adds.push(...schemaChanges.adds.map(x => ({ entity: x, schemaId })));
108
70
  removes.push(...schemaChanges.removes.map(x => ({ entity: x, schemaId })));
109
71
  }
110
-
111
72
  // Do adds separate. Updates/Removes already have an id that we can reference
112
73
  // Default can do the same as updates/removes below since it has an id
113
74
  // Check again now to see if we have any identity schema changes
114
75
  if (updates.length === 0 && removes.length === 0 && adds.length === 0) {
115
- done(Result.success())
76
+ done(results_1.Result.success());
116
77
  return;
117
78
  }
118
-
119
79
  this._doWork((db, d) => {
120
80
  try {
121
-
122
81
  const updatedDocuments = [...updates].map(w => w.change.entity);
123
- const errors: any[] = [];
124
-
82
+ const errors = [];
125
83
  db.bulkDocs([...removes.map(w => ({ _id: w.entity._id, _rev: w.entity._rev, _deleted: true })), ...updatedDocuments], null, (error, response) => {
126
-
127
84
  if (error) {
128
- d(Result.error(error));
85
+ d(results_1.Result.error(error));
129
86
  return;
130
87
  }
131
-
132
88
  for (let i = 0, length = response.length; i < length; i++) {
133
89
  const doc = response[i];
134
-
135
90
  if ("error" in doc && doc.error === true) {
136
91
  errors.push(doc); // send back the entire error
137
92
  continue;
138
93
  }
139
-
140
94
  if ("id" in doc && "ok" in doc) {
141
95
  const updatesIndex = updates.findIndex(x => x.change.entity._id === doc.id);
142
-
143
96
  if (updatesIndex !== -1) {
144
97
  // Optimistically assume that the update worked as expected
145
98
  const update = updates[updatesIndex];
146
-
147
99
  const changesResult = result.get(update.schemaId);
148
-
149
100
  // Set the new rev
150
- (update.change.entity as UnknownRecord)._rev = doc.rev;
151
-
101
+ update.change.entity._rev = doc.rev;
152
102
  changesResult.updates.push(update.change.entity);
153
103
  continue;
154
104
  }
155
-
156
105
  const removesIndex = removes.findIndex(x => x.entity._id === doc.id);
157
-
158
106
  if (removesIndex !== -1) {
159
-
160
107
  const remove = removes[removesIndex];
161
-
162
108
  const changesResult = result.get(remove.schemaId);
163
-
164
109
  changesResult.removes.push(remove.entity);
165
110
  }
166
111
  }
167
112
  }
168
-
169
113
  if (errors.length > 0) {
170
- d(Result.error(errors));
114
+ d(results_1.Result.error(errors));
171
115
  return;
172
116
  }
173
-
174
- const pipeline = new WorkPipeline();
175
-
117
+ const pipeline = new pipeline_1.WorkPipeline();
176
118
  for (let i = 0, length = identitySchemaIds.length; i < length; i++) {
177
119
  const schemaId = identitySchemaIds[i];
178
120
  pipeline.pipe((d) => {
179
121
  const schemaAdds = adds.filter(x => x.schemaId === schemaId).map(x => x.entity);
180
122
  const schemaResult = result.get(schemaId);
181
-
182
- assertIsNotNull(schemaResult);
183
- assertIsNotNull(schemaAdds);
184
-
123
+ (0, assertions_1.assertIsNotNull)(schemaResult);
124
+ (0, assertions_1.assertIsNotNull)(schemaAdds);
185
125
  db.bulkDocs([...schemaAdds], null, (error, response) => {
186
-
187
126
  if (error) {
188
- d(Result.error(error));
127
+ d(results_1.Result.error(error));
189
128
  return;
190
129
  }
191
-
192
130
  const ids = response.map(x => x.id);
193
-
194
131
  for (let i = 0, length = response.length; i < length; i++) {
195
-
196
132
  const doc = response[i];
197
-
198
133
  if ("error" in doc) {
199
-
200
134
  const reason = doc.reason ?? doc.error;
201
-
202
- d(Result.error(reason));
135
+ d(results_1.Result.error(reason));
203
136
  return;
204
137
  }
205
-
206
138
  if ("id" in doc && "ok" in doc) {
207
139
  ids.push(doc.id);
208
- } else {
209
- d(Result.error(doc.error));
140
+ }
141
+ else {
142
+ d(results_1.Result.error(doc.error));
210
143
  return;
211
144
  }
212
145
  }
213
-
214
146
  this._bulkGetAdditions(ids, (bulkGetResponse) => {
215
-
216
- if (bulkGetResponse.ok !== Result.SUCCESS) {
217
- d(Result.error(bulkGetResponse));
147
+ if (bulkGetResponse.ok !== results_1.Result.SUCCESS) {
148
+ d(results_1.Result.error(bulkGetResponse));
218
149
  return;
219
150
  }
220
-
221
151
  for (let i = 0, length = bulkGetResponse.data.results.length; i < length; i++) {
222
152
  const docs = bulkGetResponse.data.results[i].docs;
223
-
224
153
  if (docs.length === 1) {
225
154
  const doc = docs[0];
226
-
227
155
  if ("ok" in doc) {
228
- schemaResult.adds.push(doc.ok as any);
156
+ schemaResult.adds.push(doc.ok);
229
157
  }
230
158
  }
231
159
  }
232
-
233
- d(Result.success());
160
+ d(results_1.Result.success());
234
161
  });
235
162
  });
236
-
237
163
  });
238
164
  }
239
-
240
165
  pipeline.filter((r) => {
241
- if (r.ok !== Result.SUCCESS) {
166
+ if (r.ok !== results_1.Result.SUCCESS) {
242
167
  d(r);
243
168
  return;
244
169
  }
245
-
246
- d(Result.success());
170
+ d(results_1.Result.success());
247
171
  });
248
172
  });
249
- } catch (e) {
250
- d(Result.error(e));
173
+ }
174
+ catch (e) {
175
+ d(results_1.Result.error(e));
251
176
  }
252
177
  }, done);
253
178
  }
254
-
255
- private _defaultBulkOperations(nonIdentitySchemaIds: SchemaId[], changes: BulkPersistChanges, result: BulkPersistResult, done: CallbackResult<never>): void {
256
-
179
+ _defaultBulkOperations(nonIdentitySchemaIds, changes, result, done) {
257
180
  if (changes.aggregate.size === 0) {
258
- done(Result.success())
181
+ done(results_1.Result.success());
259
182
  return;
260
183
  }
261
-
262
184
  // Link each entity to a schema id below so we can easily look up the schema id for an entity
263
- const updates: { change: EntityUpdateInfo<UnknownRecord>, schemaId: SchemaId }[] = [];
264
- const adds: { entity: InferCreateType<UnknownRecord>, schemaId: SchemaId }[] = [];
265
- const removes: { entity: InferType<UnknownRecord>, schemaId: SchemaId }[] = [];
266
-
185
+ const updates = [];
186
+ const adds = [];
187
+ const removes = [];
267
188
  for (const [schemaId, schemaChanges] of changes) {
268
-
269
189
  if (nonIdentitySchemaIds.includes(schemaId) === false || schemaChanges.hasItems === false) {
270
190
  continue;
271
191
  }
272
-
273
192
  updates.push(...schemaChanges.updates.map(x => ({ change: x, schemaId })));
274
193
  adds.push(...schemaChanges.adds.map(x => ({ entity: x, schemaId })));
275
194
  removes.push(...schemaChanges.removes.map(x => ({ entity: x, schemaId })));
276
195
  }
277
-
278
196
  if (updates.length === 0 && removes.length === 0 && adds.length === 0) {
279
- done(Result.success())
197
+ done(results_1.Result.success());
280
198
  return;
281
199
  }
282
-
283
200
  this._doWork((db, d) => {
284
201
  try {
285
-
286
202
  db.bulkDocs([
287
203
  ...removes.map(x => ({ _id: x.entity._id, _rev: x.entity._rev, _deleted: true })),
288
204
  ...updates.map(x => x.change.entity)
289
205
  ], null, (error, response) => {
290
-
291
206
  if (error != null) {
292
- d(Result.error(error));
207
+ d(results_1.Result.error(error));
293
208
  return;
294
209
  }
295
-
296
210
  for (let i = 0, length = response.length; i < length; i++) {
297
211
  const doc = response[i];
298
-
299
212
  if ("error" in doc) {
300
-
301
213
  const reason = doc.reason ?? doc.error;
302
-
303
- d(Result.error(reason));
214
+ d(results_1.Result.error(reason));
304
215
  return;
305
216
  }
306
-
307
217
  const removesIndex = removes.findIndex(x => x.entity._id === doc.id);
308
-
309
218
  if (removesIndex !== -1) {
310
- const { schemaId } = removes[removesIndex]
219
+ const { schemaId } = removes[removesIndex];
311
220
  const schemaResult = result.get(schemaId);
312
-
313
- assertIsNotNull(schemaResult);
314
-
315
- schemaResult.removes.push(doc as any);
221
+ (0, assertions_1.assertIsNotNull)(schemaResult);
222
+ schemaResult.removes.push(doc);
316
223
  continue;
317
224
  }
318
-
319
225
  const updatesIndex = updates.findIndex(x => x.change.entity._id === doc.id);
320
-
321
226
  if (updatesIndex !== -1) {
322
227
  // Optimistically assume that the update worked as expected
323
228
  const update = updates[updatesIndex];
324
-
325
229
  const changesResult = result.get(update.schemaId);
326
-
327
230
  // Set the new rev
328
- (update.change.entity as UnknownRecord)._rev = doc.rev;
329
-
231
+ update.change.entity._rev = doc.rev;
330
232
  changesResult.updates.push(update.change.entity);
331
233
  continue;
332
234
  }
333
-
334
- d(Result.error(new Error("Cannot classify resulting doc")));
235
+ d(results_1.Result.error(new Error("Cannot classify resulting doc")));
335
236
  return;
336
237
  }
337
-
338
- const pipeline = new WorkPipeline();
339
-
238
+ const pipeline = new pipeline_1.WorkPipeline();
340
239
  for (let i = 0, length = nonIdentitySchemaIds.length; i < length; i++) {
341
240
  const schemaId = nonIdentitySchemaIds[i];
342
241
  pipeline.pipe((d) => {
343
242
  const schemaAdds = adds.filter(x => x.schemaId === schemaId).map(x => x.entity);
344
243
  const schemaResult = result.get(schemaId);
345
-
346
- assertIsNotNull(schemaResult);
347
- assertIsNotNull(schemaAdds);
348
-
244
+ (0, assertions_1.assertIsNotNull)(schemaResult);
245
+ (0, assertions_1.assertIsNotNull)(schemaAdds);
349
246
  db.bulkDocs([...schemaAdds], null, (error, response) => {
350
-
351
247
  if (error) {
352
- d(Result.error(error));
248
+ d(results_1.Result.error(error));
353
249
  return;
354
250
  }
355
-
356
251
  const ids = response.map(x => x.id);
357
-
358
252
  for (let i = 0, length = response.length; i < length; i++) {
359
-
360
253
  const doc = response[i];
361
-
362
254
  if ("error" in doc) {
363
-
364
255
  const reason = doc.reason ?? doc.error;
365
-
366
- d(Result.error(reason));
256
+ d(results_1.Result.error(reason));
367
257
  return;
368
258
  }
369
-
370
259
  if ("id" in doc && "ok" in doc) {
371
260
  ids.push(doc.id);
372
- } else {
373
- d(Result.error(doc.error));
261
+ }
262
+ else {
263
+ d(results_1.Result.error(doc.error));
374
264
  return;
375
265
  }
376
266
  }
377
-
378
267
  this._bulkGetAdditions(ids, (bulkGetResponse) => {
379
-
380
- if (bulkGetResponse.ok !== Result.SUCCESS) {
381
- d(Result.error(bulkGetResponse));
268
+ if (bulkGetResponse.ok !== results_1.Result.SUCCESS) {
269
+ d(results_1.Result.error(bulkGetResponse));
382
270
  return;
383
271
  }
384
-
385
272
  for (let i = 0, length = bulkGetResponse.data.results.length; i < length; i++) {
386
273
  const docs = bulkGetResponse.data.results[i].docs;
387
-
388
274
  if (docs.length === 1) {
389
275
  const doc = docs[0];
390
-
391
276
  if ("ok" in doc) {
392
- schemaResult.adds.push(doc.ok as any);
277
+ schemaResult.adds.push(doc.ok);
393
278
  }
394
279
  }
395
280
  }
396
-
397
- d(Result.success());
281
+ d(results_1.Result.success());
398
282
  });
399
283
  });
400
-
401
284
  });
402
285
  }
403
-
404
286
  pipeline.filter((r) => {
405
- if (r.ok !== Result.SUCCESS) {
287
+ if (r.ok !== results_1.Result.SUCCESS) {
406
288
  d(r);
407
289
  return;
408
290
  }
409
-
410
- d(Result.success());
291
+ d(results_1.Result.success());
411
292
  });
412
293
  });
413
- } catch (e) {
414
- d(Result.error(e));
294
+ }
295
+ catch (e) {
296
+ d(results_1.Result.error(e));
415
297
  }
416
298
  }, done);
417
299
  }
418
-
419
- private _prepareProperties(...properties: PropertyInfo<any>[]) {
420
-
300
+ _prepareProperties(...properties) {
421
301
  properties.sort((a, b) => a.name.localeCompare(b.name, undefined, { sensitivity: 'base' }));
422
302
  const paths = properties.map(w => w.getAssignmentPath({ parent: "doc" }));
423
303
  const viewName = `by_${paths.join("_")}`;
424
-
425
304
  return {
426
305
  properties,
427
306
  paths,
428
307
  viewName
429
- }
308
+ };
430
309
  }
431
-
432
- private resolveIndexes<TEntity extends {}, TShape extends unknown = TEntity>(event: DbPluginQueryEvent<TEntity, TShape>, done: CallbackResult<PouchDbDesignDoc | null>) {
433
-
310
+ resolveIndexes(event, done) {
434
311
  const indexes = event.operation.schema.getIndexes();
435
-
436
312
  if (indexes.length === 0) {
437
- done(Result.success(null));
313
+ done(results_1.Result.success(null));
438
314
  return;
439
315
  }
440
-
441
316
  if (cache["indexes"]) {
442
- done(Result.success(cache["indexes"] as PouchDbDesignDoc));
317
+ done(results_1.Result.success(cache["indexes"]));
443
318
  return; // Already built
444
319
  }
445
-
446
- const ddoc: PouchDbDesignDoc = {
320
+ const ddoc = {
447
321
  _id: `_design/${INDEX_NAME}`,
448
322
  views: {}
449
- }
450
-
323
+ };
451
324
  for (let i = 0, length = indexes.length; i < length; i++) {
452
325
  const index = indexes[i];
453
326
  const { viewName, paths } = this._prepareProperties(...index.properties);
454
-
455
327
  if (index.properties.length === 1) {
456
328
  const property = index.properties[0];
457
329
  const path = property.getAssignmentPath({ parent: "doc" });
@@ -461,19 +333,17 @@ export class PouchDbPlugin implements IDbPlugin {
461
333
  emit(${path});
462
334
  }
463
335
  }`
464
- }
336
+ };
465
337
  continue;
466
338
  }
467
-
468
339
  ddoc.views[viewName] = {
469
340
  map: `function(doc) {
470
341
  if (${paths.join(" && ")}) {
471
342
  emit([${paths.join(",")}]);
472
343
  }
473
344
  }`
474
- }
345
+ };
475
346
  }
476
-
477
347
  this._doWork((db, d) => {
478
348
  // change this out in the future? or make a new index, this does not return the rev which makes us need to call get again below
479
349
  db.allDocs({
@@ -481,329 +351,251 @@ export class PouchDbPlugin implements IDbPlugin {
481
351
  endkey: '_design0',
482
352
  include_docs: true
483
353
  }).then(response => {
484
-
485
354
  // if we have no indexes, let's create it
486
355
  if (response.rows.length === 0) {
487
- db.put(ddoc as any, {}, (e) => {
356
+ db.put(ddoc, {}, (e) => {
488
357
  if (e) {
489
- d(Result.error(e));
358
+ d(results_1.Result.error(e));
490
359
  return;
491
360
  }
492
-
493
361
  cache["indexes"] = ddoc;
494
-
495
- d(Result.success(ddoc));
362
+ d(results_1.Result.success(ddoc));
496
363
  });
497
364
  return;
498
365
  }
499
-
500
366
  const matchingIndex = response.rows.find(x => x.id === `_design/${INDEX_NAME}`);
501
-
502
367
  // make sure we have the correct index created
503
368
  if (matchingIndex == null) {
504
- db.put(ddoc as any, {}, (e) => {
369
+ db.put(ddoc, {}, (e) => {
505
370
  if (e) {
506
- d(Result.error(e));
371
+ d(results_1.Result.error(e));
507
372
  return;
508
373
  }
509
-
510
374
  cache["indexes"] = ddoc;
511
-
512
- d(Result.success(ddoc));
375
+ d(results_1.Result.success(ddoc));
513
376
  });
514
377
  return;
515
378
  }
516
-
517
- assertIsNotNull(ddoc.views);
518
- assertIsNotNull(matchingIndex.doc);
519
-
520
- const views = Object.keys(ddoc.views)
521
-
379
+ (0, assertions_1.assertIsNotNull)(ddoc.views);
380
+ (0, assertions_1.assertIsNotNull)(matchingIndex.doc);
381
+ const views = Object.keys(ddoc.views);
522
382
  // make sure all of the views are in the document, if not update it
523
- if (views.some(x => (matchingIndex.doc as any).views[x] == null)) {
524
-
383
+ if (views.some(x => matchingIndex.doc.views[x] == null)) {
525
384
  // need to get the rev
526
385
  db.get(ddoc._id, {}, (e, result) => {
527
-
528
386
  if (e != null) {
529
- d(Result.error(e));
387
+ d(results_1.Result.error(e));
530
388
  return;
531
389
  }
532
-
533
- (result as any).views = ddoc.views
534
-
535
- db.put(result as any, {}, (e) => {
536
-
390
+ result.views = ddoc.views;
391
+ db.put(result, {}, (e) => {
537
392
  if (e) {
538
- d(Result.error(e));
393
+ d(results_1.Result.error(e));
539
394
  return;
540
395
  }
541
-
542
396
  cache["indexes"] = ddoc;
543
-
544
- d(Result.success(ddoc));
397
+ d(results_1.Result.success(ddoc));
545
398
  });
546
- })
399
+ });
547
400
  return;
548
401
  }
549
-
550
- d(Result.success(ddoc));
402
+ d(results_1.Result.success(ddoc));
551
403
  }).catch(e => {
552
- d(Result.error(e));
404
+ d(results_1.Result.error(e));
553
405
  });
554
- }, done)
406
+ }, done);
555
407
  }
556
-
557
408
  // id should be a string here because this is only run on identity inserts
558
- private _bulkGetAdditions<TEntity extends {}>(ids: string[], done: CallbackResult<PouchDB.Core.BulkGetResponse<TEntity>>) {
559
-
409
+ _bulkGetAdditions(ids, done) {
560
410
  if (ids.length === 0) {
561
- done(Result.success({ results: [] }));
411
+ done(results_1.Result.success({ results: [] }));
562
412
  return;
563
413
  }
564
-
565
414
  this._doWork((db, d) => {
566
- db.bulkGet<TEntity>({
567
- docs: ids.map(w => ({ id: w as string }))
415
+ db.bulkGet({
416
+ docs: ids.map(w => ({ id: w }))
568
417
  }, (error, response) => {
569
-
570
418
  if (error) {
571
- d(Result.error(error));
572
- return
419
+ d(results_1.Result.error(error));
420
+ return;
573
421
  }
574
-
575
- d(Result.success(response));
422
+ d(results_1.Result.success(response));
576
423
  });
577
424
  }, done);
578
425
  }
579
-
580
- private _validateSchemas(event: DbPluginBulkPersistEvent) {
426
+ _validateSchemas(event) {
581
427
  for (const [, schema] of event.schemas) {
582
428
  if (schema.idProperties.length > 1) {
583
- throw new Error("PouchDB cannot have more than one key per document. Only '_id' is allowed to be the key")
429
+ throw new Error("PouchDB cannot have more than one key per document. Only '_id' is allowed to be the key");
584
430
  }
585
431
  }
586
432
  }
587
-
588
- private _bulkPersist(
589
- event: DbPluginBulkPersistEvent,
590
- done: PluginEventCallbackPartialResult<BulkPersistResult>) {
591
-
433
+ _bulkPersist(event, done) {
592
434
  this._validateSchemas(event);
593
- this._tryStartSync(event.schemas);
594
-
595
435
  const result = event.operation.toResult();
596
- const identitySchemaIds: SchemaId[] = [];
597
- const defaultSchemaIds: SchemaId[] = [];
598
-
436
+ const identitySchemaIds = [];
437
+ const defaultSchemaIds = [];
599
438
  for (const [schemaId, schema] of event.schemas) {
600
-
601
439
  if (schema.hasIdentityKeys) {
602
440
  identitySchemaIds.push(schemaId);
603
441
  continue;
604
442
  }
605
-
606
443
  defaultSchemaIds.push(schemaId);
607
444
  }
608
-
609
445
  this._identityBulkOperations(identitySchemaIds, event.operation, result, (identityResult) => {
610
-
611
- if (identityResult.ok !== Result.SUCCESS) {
612
- done(PluginEventResult.error(event.id, identityResult.error))
446
+ if (identityResult.ok !== results_1.Result.SUCCESS) {
447
+ done(results_1.PluginEventResult.error(event.id, identityResult.error));
613
448
  return;
614
449
  }
615
-
616
450
  this._defaultBulkOperations(defaultSchemaIds, event.operation, result, (defaultResult) => {
617
-
618
- if (defaultResult.ok !== Result.SUCCESS) {
619
- done(PluginEventResult.error(event.id, defaultResult.error))
451
+ if (defaultResult.ok !== results_1.Result.SUCCESS) {
452
+ done(results_1.PluginEventResult.error(event.id, defaultResult.error));
620
453
  return;
621
454
  }
622
-
623
- done(PluginEventResult.success(event.id, result))
455
+ done(results_1.PluginEventResult.success(event.id, result));
624
456
  });
625
-
626
457
  });
627
458
  }
628
-
629
- private _doWork<TResult, TEntity>(work: (db: PouchDB.Database<TEntity>, done: CallbackResult<TResult>) => void, done: CallbackResult<TResult>, shouldClose: boolean = false) {
459
+ _doWork(work, done, shouldClose = false) {
630
460
  const { sync, queryType, ...rest } = this._options ?? {};
631
- const db = new PouchDB<TEntity>(this._name, rest);
632
-
461
+ const db = new pouchdb_1.default(this._name, rest);
633
462
  work(db, (result) => {
634
-
635
463
  if (shouldClose) {
636
464
  db.close(() => done(result));
637
465
  }
638
-
639
466
  done(result);
640
- })
467
+ });
641
468
  }
642
-
643
- destroy(_event: DbPluginEvent, done: (error?: any) => void): void {
469
+ destroy(_event, done) {
644
470
  // this needs to be queued too
645
471
  this._doWork((w, d) => {
646
472
  w.destroy(null, (e) => {
647
473
  if (e) {
648
- d(Result.error(e))
474
+ d(results_1.Result.error(e));
649
475
  return;
650
476
  }
651
-
652
- d(Result.success());
477
+ d(results_1.Result.success());
653
478
  });
654
479
  }, done, false);
655
480
  }
656
-
657
-
658
- bulkPersist(
659
- event: DbPluginBulkPersistEvent,
660
- done: PluginEventCallbackPartialResult<BulkPersistResult>) {
661
-
662
- const unitOfWork: SyncronousUnitOfWork = (d) => this._bulkPersist(event, (r) => {
481
+ bulkPersist(event, done) {
482
+ const unitOfWork = (d) => this._bulkPersist(event, (r) => {
663
483
  d();
664
- done(r)
665
- })
666
-
484
+ done(r);
485
+ });
667
486
  queue.enqueue(unitOfWork.bind(this));
668
487
  }
669
-
670
- query<TRoot extends {}, TShape extends any = TRoot>(event: DbPluginQueryEvent<TRoot, TShape>, done: PluginEventCallbackResult<TShape>): void {
671
-
672
- this._tryStartSync(event.schemas);
673
-
674
- const unitOfWork: SyncronousUnitOfWork = (d) => this._query<TRoot, TShape>(event, (r) => {
488
+ query(event, done) {
489
+ const unitOfWork = (d) => this._query(event, (r) => {
675
490
  d();
676
- done(r)
677
- })
678
-
491
+ done(r);
492
+ });
679
493
  queue.enqueue(unitOfWork.bind(this));
680
494
  }
681
-
682
- protected onGetIndex<TEntity extends {}, TShape extends unknown = TEntity>(_: IQuery<TEntity, TShape>, __: PouchDB.Find.FindRequest<unknown>, done: (result: null | string | [string, string]) => void) {
495
+ onGetIndex(_, __, done) {
683
496
  done(null);
684
497
  }
685
-
686
- extractEqualityValueForProperty(expression: Expression, prop: PropertyInfo<any>): any | undefined {
498
+ extractEqualityValueForProperty(expression, prop) {
687
499
  // Recursively search for a comparator expression that matches the property
688
- if (expression.type === "comparator" && (expression as ComparatorExpression).comparator === "equals") {
500
+ if (expression.type === "comparator" && expression.comparator === "equals") {
689
501
  // Check left side is property, right side is value
690
- if (expression.left && expression.left.type === "property" && (expression.left as any).property.name === prop.name && expression.right && expression.right.type === "value") {
691
- return (expression.right as any).value;
502
+ if (expression.left && expression.left.type === "property" && expression.left.property.name === prop.name && expression.right && expression.right.type === "value") {
503
+ return expression.right.value;
692
504
  }
693
505
  // Or right side is property, left side is value
694
- if (expression.right && expression.right.type === "property" && (expression.right as any).property.name === prop.name && expression.left && expression.left.type === "value") {
695
- return (expression.left as any).value;
506
+ if (expression.right && expression.right.type === "property" && expression.right.property.name === prop.name && expression.left && expression.left.type === "value") {
507
+ return expression.left.value;
696
508
  }
697
509
  }
698
510
  // Recursively check left and right
699
511
  if (expression.left) {
700
512
  const left = this.extractEqualityValueForProperty(expression.left, prop);
701
- if (left !== undefined) return left;
513
+ if (left !== undefined)
514
+ return left;
702
515
  }
703
516
  if (expression.right) {
704
517
  const right = this.extractEqualityValueForProperty(expression.right, prop);
705
- if (right !== undefined) return right;
518
+ if (right !== undefined)
519
+ return right;
706
520
  }
707
521
  return undefined;
708
522
  }
709
-
710
- private _findMatchingIndex(ddoc: PouchDbDesignDoc, expression: Expression): MatchingIndex {
711
- const queryProperties = getProperties(expression);
712
-
523
+ _findMatchingIndex(ddoc, expression) {
524
+ const queryProperties = (0, expressions_1.getProperties)(expression);
713
525
  const { viewName } = this._prepareProperties(...queryProperties);
714
-
715
526
  if (ddoc.views == null) {
716
527
  return null;
717
528
  }
718
-
719
529
  const index = ddoc.views[viewName];
720
-
721
530
  if (index == null) {
722
531
  return null;
723
532
  }
724
-
725
- const properties: MatchingIndex["properties"] = [];
726
-
533
+ const properties = [];
727
534
  for (const property of queryProperties) {
728
535
  const value = this.extractEqualityValueForProperty(expression, property);
729
-
730
536
  if (value === undefined) {
731
- return null
537
+ return null;
732
538
  }
733
-
734
539
  properties.push({
735
540
  property,
736
541
  value
737
542
  });
738
543
  }
739
-
740
544
  return {
741
545
  viewName,
742
546
  properties
743
547
  };
744
548
  }
745
-
746
- private _queryIndex<TEntity extends {}, TShape extends unknown = TEntity>(event: DbPluginQueryEvent<TEntity, TShape>, matchingIndex: MatchingIndex, done: CallbackResult<TShape>) {
747
- const translator = new PouchDbTranslator<TEntity, TShape>(event.operation);
549
+ _queryIndex(event, matchingIndex, done) {
550
+ const translator = new PouchDbTranslator_1.PouchDbTranslator(event.operation);
748
551
  this._doWork((w, d) => {
749
-
750
- const options: PouchDB.Query.Options<any, any> = {
552
+ const options = {
751
553
  include_docs: true,
752
554
  };
753
-
754
555
  const values = matchingIndex.properties.map(x => x.value);
755
-
756
556
  if (values.some(x => x == null) == false) {
757
-
758
557
  if (values.length === 1) {
759
558
  options.key = values[0];
760
- } else {
559
+ }
560
+ else {
761
561
  options.keys = values;
762
562
  }
763
563
  }
764
-
765
564
  w.query(`${INDEX_NAME}/${matchingIndex.viewName}`, options, (error, response) => {
766
-
767
565
  if (error != null) {
768
- d(Result.error(error));
566
+ d(results_1.Result.error(error));
769
567
  return;
770
568
  }
771
-
772
569
  const translated = translator.translate(response.rows.map(w => w.doc));
773
- d(Result.success(translated));
570
+ d(results_1.Result.success(translated));
774
571
  });
775
572
  }, done);
776
573
  }
777
-
778
- private _queryNoIndex<TEntity extends {}, TShape extends unknown = TEntity>(event: DbPluginQueryEvent<TEntity, TShape>, done: CallbackResult<TShape>) {
779
- const filters = event.operation.options.get("filter")
574
+ _queryNoIndex(event, done) {
575
+ const filters = event.operation.options.get("filter");
780
576
  if (filters.length === 0) {
781
577
  this._queryWithNoFilters(event, done);
782
578
  return;
783
579
  }
784
-
785
580
  this._queryWithFilters(event, done);
786
581
  }
787
-
788
- private _queryWithNoFilters<TEntity extends {}, TShape extends unknown = TEntity>(event: DbPluginQueryEvent<TEntity, TShape>, done: CallbackResult<TShape>) {
789
- const translator = new PouchDbTranslator<TEntity, TShape>(event.operation);
582
+ _queryWithNoFilters(event, done) {
583
+ const translator = new PouchDbTranslator_1.PouchDbTranslator(event.operation);
790
584
  this._doWork((w, d) => {
791
585
  w.allDocs({
792
586
  include_docs: true
793
587
  }).then(response => {
794
588
  const data = response.rows.map(w => w.doc);
795
589
  const translated = translator.translate(data);
796
- d(Result.success(translated));
590
+ d(results_1.Result.success(translated));
797
591
  }).catch(error => {
798
- d(Result.error(error));
592
+ d(results_1.Result.error(error));
799
593
  });
800
594
  }, done);
801
595
  }
802
-
803
- private _queryWithFilters<TEntity extends {}, TShape extends unknown = TEntity>(event: DbPluginQueryEvent<TEntity, TShape>, done: CallbackResult<TShape>) {
804
- const translator = new PouchDbTranslator<TEntity, TShape>(event.operation);
596
+ _queryWithFilters(event, done) {
597
+ const translator = new PouchDbTranslator_1.PouchDbTranslator(event.operation);
805
598
  this._doWork((w, d) => {
806
-
807
599
  if (this._name.startsWith("http")) {
808
600
  // Cannot query remote databases using translator.matches, fallback to alldocs
809
601
  // Does not throw, will fail on the remote server
@@ -812,119 +604,92 @@ export class PouchDbPlugin implements IDbPlugin {
812
604
  }).then(response => {
813
605
  const data = response.rows.map(w => w.doc);
814
606
  const translated = translator.translate(data);
815
- d(Result.success(translated));
607
+ d(results_1.Result.success(translated));
816
608
  }).catch(error => {
817
- d(Result.error(error));
609
+ d(results_1.Result.error(error));
818
610
  });
819
611
  return;
820
612
  }
821
-
822
- w.query<{}, any>((doc, emit) => {
613
+ w.query((doc, emit) => {
823
614
  if (typeof doc === "object" && "_id" in doc && translator.matches(doc)) {
824
615
  emit(doc._id, doc);
825
616
  }
826
617
  }, (error, response) => {
827
-
828
618
  if (error != null) {
829
- d(Result.error(error));
619
+ d(results_1.Result.error(error));
830
620
  return;
831
621
  }
832
-
833
622
  const data = response.rows.map(w => w.value);
834
623
  const translated = translator.translate(data);
835
- d(Result.success(translated));
624
+ d(results_1.Result.success(translated));
836
625
  });
837
-
838
626
  }, done);
839
627
  }
840
-
841
- private _query<TEntity extends {}, TShape extends unknown = TEntity>(event: DbPluginQueryEvent<TEntity, TShape>, done: PluginEventCallbackResult<TShape>): void {
628
+ _query(event, done) {
842
629
  this.resolveIndexes(event, (r) => {
843
- if (r.ok !== Result.SUCCESS) {
844
- done(PluginEventResult.error(event.id, r.error))
630
+ if (r.ok !== results_1.Result.SUCCESS) {
631
+ done(results_1.PluginEventResult.error(event.id, r.error));
845
632
  return;
846
633
  }
847
-
848
634
  const ddoc = r.data;
849
-
850
635
  if (ddoc == null) {
851
636
  this._queryNoIndex(event, done);
852
637
  return;
853
638
  }
854
-
855
639
  const mapMatchingIndex = this.findMatchingIndexForMap(ddoc, event);
856
-
857
640
  if (mapMatchingIndex != null) {
858
641
  this._queryIndex(event, mapMatchingIndex, done);
859
642
  return;
860
643
  }
861
-
862
644
  const expression = this._getExpressionFromQuery(event);
863
-
864
- if (Expression.isEmpty(expression)) {
645
+ if (expressions_1.Expression.isEmpty(expression)) {
865
646
  this._queryNoIndex(event, done);
866
647
  return;
867
648
  }
868
-
869
649
  const matchingIndex = this._findMatchingIndex(ddoc, expression);
870
-
871
650
  if (matchingIndex == null) {
872
651
  this._queryNoIndex(event, done);
873
652
  return;
874
653
  }
875
-
876
654
  this._queryIndex(event, matchingIndex, done);
877
655
  });
878
656
  }
879
-
880
- private _getExpressionFromQuery<TEntity extends {}, TShape>(event: DbPluginQueryEvent<TEntity, TShape>) {
657
+ _getExpressionFromQuery(event) {
881
658
  const filters = event.operation.options.get("filter");
882
-
883
659
  const databaseFilters = filters.filter(x => x.option.target === "database");
884
-
885
660
  if (databaseFilters.length === 0) {
886
- return Expression.EMPTY;
661
+ return expressions_1.Expression.EMPTY;
887
662
  }
888
-
889
663
  const expressions = databaseFilters.map(x => x.option.value.expression);
890
-
891
- return combineExpressions(...expressions);
664
+ return (0, expressions_1.combineExpressions)(...expressions);
892
665
  }
893
-
894
- private findMatchingIndexForMap<TEntity extends {}, TShape>(ddoc: PouchDbDesignDoc, event: DbPluginQueryEvent<TEntity, TShape>): MatchingIndex | null {
666
+ findMatchingIndexForMap(ddoc, event) {
895
667
  const map = event.operation.options.getLast("map");
896
668
  const filters = event.operation.options.get("filter");
897
-
898
669
  // we only want to look at the index if there are no filters
899
670
  if (filters.length > 0) {
900
671
  return null;
901
672
  }
902
-
903
673
  if (map == null || map.target !== "database") {
904
674
  return null;
905
675
  }
906
-
907
676
  if (map.value.fields.length !== 1 || map.value.fields[0].property == null) {
908
677
  return null;
909
678
  }
910
-
911
679
  const property = map.value.fields[0].property;
912
-
913
680
  const { viewName } = this._prepareProperties(property);
914
-
915
681
  if (ddoc.views == null) {
916
682
  return null;
917
683
  }
918
-
919
684
  const index = ddoc.views[viewName];
920
-
921
685
  if (index == null) {
922
686
  return null;
923
687
  }
924
-
925
688
  return {
926
689
  viewName,
927
690
  properties: [{ property, value: null }]
928
- }
691
+ };
929
692
  }
930
- }
693
+ }
694
+ exports.PouchDbPlugin = PouchDbPlugin;
695
+ //# sourceMappingURL=PouchDbPlugin.js.map