All files replication.js

91.3% Statements 84/92
82.05% Branches 32/39
91.67% Functions 22/24
92.68% Lines 76/82

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196                                          40x 40x 12x   12x 12x 12x 12x 12x         12x       38x 38x 37x           37x 37x 1x   36x                   6x       12x 12x 12x 12x     2x 2x     12x 12x 12x 12x 12x 12x     3x     11x   11x 11x 8x 8x     3x 3x 3x   3x 3x         3x       24x   24x 24x 24x   24x 6x 6x     24x 24x   24x 24x       11x 11x 11x 12x                         12x 11x   11x 12x   32x   32x   7x 8x   7x 7x 7x       11x   11x   11x       14x 14x 14x                           14x         14x   11x      
import { PouchDB } from 'rxdb';
import { BehaviorSubject } from 'rxjs';
import keyCompression from 'rxdb/plugins/key-compression';
 
export default {
  rxdb: true,
  prototypes: {},
  overwritable: {
    createKeyCompressor(...args) {
      const ans = keyCompression.overwritable.createKeyCompressor(...args);
 
      ans._table = {
        ...ans.table,
        rx_model: 'rx_model'
      };
 
      return ans;
    }
  },
  hooks: {
    createRxDatabase(database) {
      database.replications = [];
      database.replicate = function replicate(...args) {
        const replication = new Replication(database.collections, ...args);
 
        database.replications.push(replication);
        const index = database.replications.length - 1;
        replication.destroy = async function destroy() {
          await replication.close();
          database.replications = database.replications
            .slice(0, index)
            .concat(database.replications.slice(index + 1));
        };
 
        return replication;
      };
    },
    preCreateRxCollection(model) {
      const name = model.name;
      if (!name) throw Error('RxCollection(s) must have a "name" property');
      Iif (!model.schema || !model.schema.properties) {
        throw Error(
          'RxCollection(s) must have a a "schema" property, with a "properties" key'
        );
      }
 
      const rxModel = model.schema.properties.rx_model;
      if (rxModel && (rxModel.type !== 'string' || rxModel.default !== name)) {
        throw Error('Schema properties cannot be called "rx_model"');
      }
      model.schema.properties.rx_model = {
        type: 'string',
        enum: [name],
        default: name
      };
    }
  }
};
 
const isDevelopment =
  (process.env.NODE_ENV !== 'production' && process.env.NODE_ENV !== 'test') ||
  process.env.NODE_ENV === 'development';
class Replication {
  constructor(collections, remote, collectionNames, direction, options = {}) {
    this.remote = remote;
    this.directon = direction;
    this.options = options;
    this.collections = !collectionNames
      ? collections
      : collectionNames.reduce((acc, key) => {
          if (collections[key]) acc[key] = collections[key];
          return acc;
        }, {});
 
    this.replicationStates = [];
    this._pReplicationStates = Promise.resolve([]);
    this._subscribers = [];
    this._states = [];
    this.alive = false;
    this._aliveSubject = new BehaviorSubject(false);
  }
  get alive$() {
    return this._aliveSubject.asObservable();
  }
  async connect() {
    await this.close();
 
    try {
      await this._createFilter(this.remote);
      await this._sync();
      return true;
    } catch (e) {
      // eslint-disable-next-line no-console
      Iif (isDevelopment) console.error(e);
      this._interval = setInterval(() => {
        this._createFilter(this.remote)
          .then(() => {
            clearInterval(this._interval);
            this._sync();
          })
          // eslint-disable-next-line no-console
          .catch((e) => isDevelopment && console.error(e));
      }, 5000);
      return false;
    }
  }
  async close() {
    clearInterval(this._interval);
 
    this._subscribers.forEach((x) => x.unsubscribe());
    this._subscribers = [];
    this._states = [];
 
    if (this.alive) {
      this.alive = false;
      this._aliveSubject.next(false);
    }
 
    await this._pReplicationStates.then((arr) => {
      return Promise.all(arr.map((x) => x.cancel()));
    });
    this._pReplicationStates = Promise.resolve([]);
    this.replicationStates = [];
  }
  // Private
  async _sync() {
    const collections = this.collections;
    const collectionNames = Object.keys(collections);
    const promises = collectionNames.map((name) => {
      return collections[name].sync({
        remote: this.remote,
        direction: this.direction,
        options: {
          ...this.options,
          live: this.options.live || true,
          retry: this.options.retry || true,
          filter: 'app/by_model',
          query_params: { rx_model: name }
        }
      });
    });
 
    const allAlive = promises.map(() => false);
    this._pReplicationStates = Promise.all(promises)
      .then((arr) => {
        arr.forEach((rep, i) => {
          this._subscribers.push(
            rep.alive$.subscribe((val) => {
              const repAlive = allAlive[i];
 
              if (repAlive === val) return;
 
              allAlive[i] = val;
              const alive = allAlive.reduce((acc, x) => acc & x, true);
 
              Iif (alive === this.alive) return;
              this.alive = alive;
              this._aliveSubject.next(val);
            })
          );
        });
        return arr;
      })
      .then((arr) => (this.replicationStates = arr));
 
    await this._pReplicationStates;
  }
  async _createFilter() {
    // https://pouchdb.com/2015/04/05/filtered-replication.html
    const remoteIsUrl = typeof this.remote === 'string';
    const db = remoteIsUrl ? new PouchDB(this.remote) : this.remote;
    const doc = {
      version: 0,
      _id: '_design/app',
      filters: {
        // not doing fn.toString() as istambul code
        // on tests breaks it
        by_model: `function(doc, req) {
          return (
            doc._id === '_design/app' || doc.rx_model === req.query.rx_model
          );
        }`
      }
    };
 
    await db
      .get('_design/app')
      .then(({ version, _rev }) => {
        return version < doc.version ? db.put({ ...doc, _rev }) : true;
      })
      .catch(() => db.put(doc));
 
    if (remoteIsUrl) db.close();
  }
}