All files / src/commons optimistic-mutator.js

88.71% Statements 110/124
70.97% Branches 44/62
94.44% Functions 17/18
88.89% Lines 104/117
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 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272        1x 1x 1x 1x     16x 16x 16x   16x       16x 16x 16x   16x 16x                 6x 3x 3x   3x   3x       3x       3x       3x       3x                 1x   1x   1x 1x             2x 2x   2x 1x     1x         6x 6x   5x 1x     5x 5x 5x         5x     5x   1x     5x       5x 5x 2x     4x       2x 2x 2x   2x 2x 2x         2x 2x 2x     2x     2x   1x     2x         2x           2x       5x 5x   5x 5x 5x         5x 5x 5x     5x   1x     5x       3x 3x 1x 1x 3x         2x       5x 5x   5x 5x 5x         5x 5x     5x   1x     5x       3x 3x 1x 3x           2x       18x 1x           16x     1x         19x 59x 13x       6x       2x           12x       24x    
 
/*
 Forked from feathers-memory/src/index.js
 */
import Proto from 'uberproto';
import errors from 'feathers-errors';
import filter from 'feathers-query-filters';
import { sorter, matcher, select, _ } from 'feathers-commons';
 
class Service {
  constructor (options = {}) {
    this._replicator = options.replicator;
    this._engine = this._replicator.engine;
 
    Iif (!this._engine.useUuid) {
      throw new Error('Replicator must be configured for uuid for optimistic updates. (offline)');
    }
 
    this._mutateStore = this._engine._mutateStore.bind(this._engine);
    this._alwaysSelect = ['id', '_id', 'uuid'];
    this._getUuid = this._replicator.getUuid;
 
    this.store = this._engine.store || { records: [] };
    this.paginate = options.paginate || {};
  }
 
  extend (obj) {
    return Proto.extend(obj, this);
  }
 
  // Find without hooks and mixins that can be used internally and always returns
  // a pagination object
  _find (params, getFilter = filter) {
    const { query, filters } = getFilter(params.query || {});
    let values = _.values(this.store.records).filter(matcher(query));
 
    const total = values.length;
 
    Iif (filters.$sort) {
      values.sort(sorter(filters.$sort));
    }
 
    Iif (filters.$skip) {
      values = values.slice(filters.$skip);
    }
 
    Iif (typeof filters.$limit !== 'undefined') {
      values = values.slice(0, filters.$limit);
    }
 
    Iif (filters.$select) {
      values = values.map(value => _.pick(value, ...filters.$select));
    }
 
    return Promise.resolve({
      total,
      limit: filters.$limit,
      skip: filters.$skip || 0,
      data: values
    });
  }
 
  find (params) {
    const paginate = typeof params.paginate !== 'undefined' ? params.paginate : this.paginate;
    // Call the internal find with query parameter that include pagination
    const result = this._find(params, query => filter(query, paginate));
 
    Eif (!(paginate && paginate.default)) {
      return result.then(page => page.data);
    }
 
    return result;
  }
 
  get (uuid, params) {
    const records = this.store.records;
    const index = findUuidIndex(records, uuid);
 
    if (index === -1) {
      return Promise.reject(new errors.NotFound(`No record found for uuid '${uuid}'`));
    }
 
    return Promise.resolve(records[index])
      .then(select(params, ...this._alwaysSelect));
  }
 
  // Create without hooks and mixins that can be used internally
  _create (data, params) {
    this._checkConnected();
 
    if (!('uuid' in data)) {
      data.uuid = this._getUuid();
    }
 
    const records = this.store.records;
    const index = findUuidIndex(records, data.uuid);
    Iif (index > -1) {
      throw new errors.BadRequest('Optimistic create requires unique uuid. (offline)');
    }
 
    // optimistic mutation
    this._mutateStore('created', data, 1);
 
    // Start actual mutation on remote service
    this._replicator._service.create(shallowClone(data), params)
      .catch(() => {
        this._mutateStore('removed', data, 2);
      });
 
    return Promise.resolve(data)
      .then(select(params, ...this._alwaysSelect));
  }
 
  create (data, params) {
    if (Array.isArray(data)) {
      return Promise.all(data.map(current => this._create(current)));
    }
 
    return this._create(data, params);
  }
 
  // Update without hooks and mixins that can be used internally
  _update (uuid, data, params) {
    this._checkConnected();
    checkUuidExists(data);
 
    const records = this.store.records;
    const index = findUuidIndex(records, uuid);
    Iif (index === -1) {
      return Promise.reject(new errors.NotFound(`No record found for uuid '${uuid}'`));
    }
 
    // We don't want our id to change type if it can be coerced
    const beforeRecord = shallowClone(records[index]);
    const beforeUuid = beforeRecord.uuid;
    data.uuid = beforeUuid == uuid ? beforeUuid : uuid; // eslint-disable-line
 
    // Optimistic mutation
    this._mutateStore('updated', data, 1);
 
    // Start actual mutation on remote service
    this._replicator._service.update(getId(data), shallowClone(data), params)
      .catch(() => {
        this._mutateStore('updated', beforeRecord, 2);
      });
 
    return Promise.resolve(data)
      .then(select(params, ...this._alwaysSelect));
  }
 
  update (uuid, data, params) {
    Iif (uuid === null || Array.isArray(data)) {
      return Promise.reject(new errors.BadRequest(
        `You can not replace multiple instances. Did you mean 'patch'?`
      ));
    }
 
    return this._update(uuid, data, params);
  }
 
  // Patch without hooks and mixins that can be used internally
  _patch (uuid, data, params) {
    this._checkConnected();
 
    const records = this.store.records;
    const index = findUuidIndex(records, uuid);
    Iif (index === -1) {
      return Promise.reject(new errors.NotFound(`No record found for uuid '${uuid}'`));
    }
 
    // Optimistic mutation
    const beforeRecord = shallowClone(records[index]);
    const afterRecord = Object.assign({}, beforeRecord, data);
    this._mutateStore('patched', afterRecord, 1);
 
    // Start actual mutation on remote service
    this._replicator._service.patch(getId(beforeRecord), shallowClone(data), params)
      .catch(() => {
        this._mutateStore('updated', beforeRecord, 2);
      });
 
    return Promise.resolve(afterRecord)
      .then(select(params, ...this._alwaysSelect));
  }
 
  patch (uuid, data, params) {
    if (uuid === null) {
      return this._find(params).then(page => {
        return Promise.all(page.data.map(
          current => this._patch(current.uuid, data, params))
        );
      });
    }
 
    return this._patch(uuid, data, params);
  }
 
  // Remove without hooks and mixins that can be used internally
  _remove (uuid, params) {
    this._checkConnected();
 
    const records = this.store.records;
    const index = findUuidIndex(records, uuid);
    Iif (index === -1) {
      return Promise.reject(new errors.NotFound(`No record found for uuid '${uuid}'`));
    }
 
    // Optimistic mutation
    const beforeRecord = shallowClone(records[index]);
    this._mutateStore('removed', beforeRecord, 1);
 
    // Start actual mutation on remote service
    this._replicator._service.remove(getId(beforeRecord), params)
      .catch(() => {
        this._mutateStore('created', beforeRecord, 2);
      });
 
    return Promise.resolve(beforeRecord)
      .then(select(params, ...this._alwaysSelect));
  }
 
  remove (uuid, params) {
    if (uuid === null) {
      return this._find(params).then(page =>
        Promise.all(page.data.map(current =>
          this._remove(current.uuid, params
          )
        )));
    }
 
    return this._remove(uuid, params);
  }
 
  _checkConnected () {
    if (!this._replicator.connected) {
      throw new errors.BadRequest('Replicator not connected to remote. (offline)');
    }
  }
}
 
export default function init (options) {
  return new Service(options);
}
 
init.Service = Service;
 
// Helpers
 
function findUuidIndex (array, uuid) {
  for (let i = 0, len = array.length; i < len; i++) {
    if (array[i].uuid == uuid) { // eslint-disable-line
      return i;
    }
  }
 
  return -1;
}
 
function checkUuidExists (record) {
  Iif (!('uuid' in record)) {
    throw new errors.BadRequest('Optimistic mutation requires uuid. (offline)');
  }
}
 
function getId (record) {
  return ('id' in record ? record.id : record._id);
}
 
function shallowClone (obj) {
  return Object.assign({}, obj);
}