2016-04-15 02:07:31 +03:00
|
|
|
|
/*
|
|
|
|
|
*
|
|
|
|
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
|
|
|
* you may not use this file except in compliance with the License.
|
|
|
|
|
* You may obtain a copy of the License at
|
|
|
|
|
*
|
|
|
|
|
* http://www.apache.org/licenses/LICENSE-2.0
|
|
|
|
|
*
|
|
|
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
|
|
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
|
|
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
|
|
|
* See the License for the specific language governing permissions and
|
|
|
|
|
* limitations under the License.
|
|
|
|
|
*/
|
|
|
|
|
|
|
|
|
|
/*
|
|
|
|
|
* This file is generated from kinto.js - do not modify directly.
|
|
|
|
|
*/
|
|
|
|
|
|
2016-11-16 03:38:53 +03:00
|
|
|
|
this.EXPORTED_SYMBOLS = ["Kinto"];
|
2016-04-15 02:07:31 +03:00
|
|
|
|
|
|
|
|
|
/*
|
2017-01-28 03:23:05 +03:00
|
|
|
|
* Version 8.0.0 - 57d2836
|
2016-04-15 02:07:31 +03:00
|
|
|
|
*/
|
|
|
|
|
|
2016-11-16 03:38:53 +03:00
|
|
|
|
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.Kinto = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
|
2016-04-15 02:07:31 +03:00
|
|
|
|
/*
|
|
|
|
|
*
|
|
|
|
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
|
|
|
* you may not use this file except in compliance with the License.
|
|
|
|
|
* You may obtain a copy of the License at
|
|
|
|
|
*
|
|
|
|
|
* http://www.apache.org/licenses/LICENSE-2.0
|
|
|
|
|
*
|
|
|
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
|
|
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
|
|
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
|
|
|
* See the License for the specific language governing permissions and
|
|
|
|
|
* limitations under the License.
|
|
|
|
|
*/
|
|
|
|
|
|
|
|
|
|
"use strict";
|
|
|
|
|
|
|
|
|
|
Object.defineProperty(exports, "__esModule", {
|
|
|
|
|
value: true
|
|
|
|
|
});
|
2016-07-13 22:09:42 +03:00
|
|
|
|
|
2016-11-16 03:38:53 +03:00
|
|
|
|
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
|
2016-04-15 02:07:31 +03:00
|
|
|
|
|
|
|
|
|
var _KintoBase = require("../src/KintoBase");
|
|
|
|
|
|
|
|
|
|
var _KintoBase2 = _interopRequireDefault(_KintoBase);
|
|
|
|
|
|
|
|
|
|
var _utils = require("../src/utils");
|
|
|
|
|
|
|
|
|
|
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
|
|
|
|
|
|
|
|
|
const { classes: Cc, interfaces: Ci, utils: Cu } = Components;
|
|
|
|
|
|
2016-11-16 03:38:53 +03:00
|
|
|
|
Cu.import("resource://gre/modules/Timer.jsm");
|
|
|
|
|
Cu.importGlobalProperties(["fetch"]);
|
|
|
|
|
const { EventEmitter } = Cu.import("resource://devtools/shared/event-emitter.js", {});
|
|
|
|
|
const { generateUUID } = Cc["@mozilla.org/uuid-generator;1"].getService(Ci.nsIUUIDGenerator);
|
2016-04-15 02:07:31 +03:00
|
|
|
|
|
2016-11-16 03:38:53 +03:00
|
|
|
|
// Use standalone kinto-http module landed in FFx.
|
2017-01-28 03:23:05 +03:00
|
|
|
|
const { KintoHttpClient } = Cu.import("resource://services-common/kinto-http-client.js");
|
2016-04-15 02:07:31 +03:00
|
|
|
|
|
2016-11-16 03:38:53 +03:00
|
|
|
|
class Kinto extends _KintoBase2.default {
|
|
|
|
|
constructor(options = {}) {
|
|
|
|
|
const events = {};
|
|
|
|
|
EventEmitter.decorate(events);
|
2016-04-15 02:07:31 +03:00
|
|
|
|
|
2016-11-16 03:38:53 +03:00
|
|
|
|
const defaults = {
|
|
|
|
|
events,
|
|
|
|
|
ApiClass: KintoHttpClient
|
|
|
|
|
};
|
|
|
|
|
super(_extends({}, defaults, options));
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
collection(collName, options = {}) {
|
|
|
|
|
const idSchema = {
|
2016-04-15 02:07:31 +03:00
|
|
|
|
validate: _utils.RE_UUID.test.bind(_utils.RE_UUID),
|
|
|
|
|
generate: function () {
|
|
|
|
|
return generateUUID().toString().replace(/[{}]/g, "");
|
|
|
|
|
}
|
|
|
|
|
};
|
2016-11-16 03:38:53 +03:00
|
|
|
|
return super.collection(collName, _extends({ idSchema }, options));
|
2016-04-15 02:07:31 +03:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2016-11-16 03:38:53 +03:00
|
|
|
|
exports.default = Kinto; // This fixes compatibility with CommonJS required by browserify.
|
2016-04-15 02:07:31 +03:00
|
|
|
|
// See http://stackoverflow.com/questions/33505992/babel-6-changes-how-it-exports-default/33683495#33683495
|
2016-10-07 17:27:48 +03:00
|
|
|
|
|
2016-11-16 03:38:53 +03:00
|
|
|
|
if (typeof module === "object") {
|
|
|
|
|
module.exports = Kinto;
|
2016-10-07 17:27:48 +03:00
|
|
|
|
}
|
|
|
|
|
|
2016-11-16 03:38:53 +03:00
|
|
|
|
},{"../src/KintoBase":3,"../src/utils":7}],2:[function(require,module,exports){
|
2016-10-07 17:27:48 +03:00
|
|
|
|
|
2016-11-16 03:38:53 +03:00
|
|
|
|
},{}],3:[function(require,module,exports){
|
2016-04-15 02:07:31 +03:00
|
|
|
|
"use strict";
|
|
|
|
|
|
|
|
|
|
Object.defineProperty(exports, "__esModule", {
|
|
|
|
|
value: true
|
|
|
|
|
});
|
|
|
|
|
|
2016-11-16 03:38:53 +03:00
|
|
|
|
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
|
2016-07-13 22:09:42 +03:00
|
|
|
|
|
2016-04-15 02:07:31 +03:00
|
|
|
|
var _collection = require("./collection");
|
|
|
|
|
|
|
|
|
|
var _collection2 = _interopRequireDefault(_collection);
|
|
|
|
|
|
|
|
|
|
var _base = require("./adapters/base");
|
|
|
|
|
|
|
|
|
|
var _base2 = _interopRequireDefault(_base);
|
|
|
|
|
|
|
|
|
|
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
|
|
|
|
|
|
|
|
|
const DEFAULT_BUCKET_NAME = "default";
|
|
|
|
|
const DEFAULT_REMOTE = "http://localhost:8888/v1";
|
2017-01-18 16:53:52 +03:00
|
|
|
|
const DEFAULT_RETRY = 1;
|
2016-04-15 02:07:31 +03:00
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* KintoBase class.
|
|
|
|
|
*/
|
|
|
|
|
class KintoBase {
|
|
|
|
|
/**
|
|
|
|
|
* Provides a public access to the base adapter class. Users can create a
|
|
|
|
|
* custom DB adapter by extending {@link BaseAdapter}.
|
|
|
|
|
*
|
|
|
|
|
* @type {Object}
|
|
|
|
|
*/
|
|
|
|
|
static get adapters() {
|
|
|
|
|
return {
|
|
|
|
|
BaseAdapter: _base2.default
|
|
|
|
|
};
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Synchronization strategies. Available strategies are:
|
|
|
|
|
*
|
|
|
|
|
* - `MANUAL`: Conflicts will be reported in a dedicated array.
|
|
|
|
|
* - `SERVER_WINS`: Conflicts are resolved using remote data.
|
|
|
|
|
* - `CLIENT_WINS`: Conflicts are resolved using local data.
|
|
|
|
|
*
|
|
|
|
|
* @type {Object}
|
|
|
|
|
*/
|
|
|
|
|
static get syncStrategy() {
|
|
|
|
|
return _collection2.default.strategy;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Constructor.
|
|
|
|
|
*
|
|
|
|
|
* Options:
|
2016-07-13 22:09:42 +03:00
|
|
|
|
* - `{String}` `remote` The server URL to use.
|
|
|
|
|
* - `{String}` `bucket` The collection bucket name.
|
|
|
|
|
* - `{EventEmitter}` `events` Events handler.
|
|
|
|
|
* - `{BaseAdapter}` `adapter` The base DB adapter class.
|
|
|
|
|
* - `{Object}` `adapterOptions` Options given to the adapter.
|
|
|
|
|
* - `{String}` `dbPrefix` The DB name prefix.
|
|
|
|
|
* - `{Object}` `headers` The HTTP headers to use.
|
2017-01-18 16:53:52 +03:00
|
|
|
|
* - `{Object}` `retry` Number of retries when the server fails to process the request (default: `1`)
|
2016-07-13 22:09:42 +03:00
|
|
|
|
* - `{String}` `requestMode` The HTTP CORS mode to use.
|
|
|
|
|
* - `{Number}` `timeout` The requests timeout in ms (default: `5000`).
|
2016-04-15 02:07:31 +03:00
|
|
|
|
*
|
|
|
|
|
* @param {Object} options The options object.
|
|
|
|
|
*/
|
|
|
|
|
constructor(options = {}) {
|
|
|
|
|
const defaults = {
|
|
|
|
|
bucket: DEFAULT_BUCKET_NAME,
|
2017-01-18 16:53:52 +03:00
|
|
|
|
remote: DEFAULT_REMOTE,
|
|
|
|
|
retry: DEFAULT_RETRY
|
2016-04-15 02:07:31 +03:00
|
|
|
|
};
|
2016-11-16 03:38:53 +03:00
|
|
|
|
this._options = _extends({}, defaults, options);
|
2016-04-15 02:07:31 +03:00
|
|
|
|
if (!this._options.adapter) {
|
|
|
|
|
throw new Error("No adapter provided");
|
|
|
|
|
}
|
|
|
|
|
|
2017-01-18 16:53:52 +03:00
|
|
|
|
const { remote, events, headers, retry, requestMode, timeout, ApiClass } = this._options;
|
2016-04-15 02:07:31 +03:00
|
|
|
|
|
|
|
|
|
// public properties
|
2016-07-13 22:09:42 +03:00
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* The kinto HTTP client instance.
|
|
|
|
|
* @type {KintoClient}
|
|
|
|
|
*/
|
2017-01-18 16:53:52 +03:00
|
|
|
|
this.api = new ApiClass(remote, { events, headers, retry, requestMode, timeout });
|
2016-04-15 02:07:31 +03:00
|
|
|
|
/**
|
|
|
|
|
* The event emitter instance.
|
|
|
|
|
* @type {EventEmitter}
|
|
|
|
|
*/
|
|
|
|
|
this.events = this._options.events;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Creates a {@link Collection} instance. The second (optional) parameter
|
|
|
|
|
* will set collection-level options like e.g. `remoteTransformers`.
|
|
|
|
|
*
|
|
|
|
|
* @param {String} collName The collection name.
|
2017-01-18 16:53:52 +03:00
|
|
|
|
* @param {Object} [options={}] Extra options or override client's options.
|
|
|
|
|
* @param {Object} [options.idSchema] IdSchema instance (default: UUID)
|
|
|
|
|
* @param {Object} [options.remoteTransformers] Array<RemoteTransformer> (default: `[]`])
|
|
|
|
|
* @param {Object} [options.hooks] Array<Hook> (default: `[]`])
|
2016-04-15 02:07:31 +03:00
|
|
|
|
* @return {Collection}
|
|
|
|
|
*/
|
|
|
|
|
collection(collName, options = {}) {
|
|
|
|
|
if (!collName) {
|
|
|
|
|
throw new Error("missing collection name");
|
|
|
|
|
}
|
2017-01-18 16:53:52 +03:00
|
|
|
|
const {
|
|
|
|
|
bucket,
|
|
|
|
|
events,
|
|
|
|
|
adapter,
|
|
|
|
|
adapterOptions,
|
|
|
|
|
dbPrefix
|
|
|
|
|
} = _extends({}, this._options, options);
|
|
|
|
|
const {
|
|
|
|
|
idSchema,
|
|
|
|
|
remoteTransformers,
|
|
|
|
|
hooks
|
|
|
|
|
} = options;
|
2016-04-15 02:07:31 +03:00
|
|
|
|
|
2016-07-13 22:09:42 +03:00
|
|
|
|
return new _collection2.default(bucket, collName, this.api, {
|
2017-01-18 16:53:52 +03:00
|
|
|
|
events,
|
|
|
|
|
adapter,
|
|
|
|
|
adapterOptions,
|
|
|
|
|
dbPrefix,
|
|
|
|
|
idSchema,
|
|
|
|
|
remoteTransformers,
|
|
|
|
|
hooks
|
2016-04-15 02:07:31 +03:00
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
exports.default = KintoBase;
|
|
|
|
|
|
2016-11-16 03:38:53 +03:00
|
|
|
|
},{"./adapters/base":5,"./collection":6}],4:[function(require,module,exports){
|
2016-07-13 22:09:42 +03:00
|
|
|
|
"use strict";
|
|
|
|
|
|
|
|
|
|
Object.defineProperty(exports, "__esModule", {
|
|
|
|
|
value: true
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
var _base = require("./base.js");
|
|
|
|
|
|
|
|
|
|
var _base2 = _interopRequireDefault(_base);
|
|
|
|
|
|
|
|
|
|
var _utils = require("../utils");
|
|
|
|
|
|
|
|
|
|
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
|
|
|
|
|
2016-11-16 03:38:53 +03:00
|
|
|
|
function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; }
|
|
|
|
|
|
2016-07-13 22:09:42 +03:00
|
|
|
|
const INDEXED_FIELDS = ["id", "_status", "last_modified"];
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* IDB cursor handlers.
|
|
|
|
|
* @type {Object}
|
|
|
|
|
*/
|
|
|
|
|
const cursorHandlers = {
|
2016-10-07 17:27:48 +03:00
|
|
|
|
all(filters, done) {
|
2016-07-13 22:09:42 +03:00
|
|
|
|
const results = [];
|
|
|
|
|
return function (event) {
|
|
|
|
|
const cursor = event.target.result;
|
|
|
|
|
if (cursor) {
|
2016-10-07 17:27:48 +03:00
|
|
|
|
if ((0, _utils.filterObject)(filters, cursor.value)) {
|
|
|
|
|
results.push(cursor.value);
|
|
|
|
|
}
|
2016-07-13 22:09:42 +03:00
|
|
|
|
cursor.continue();
|
|
|
|
|
} else {
|
|
|
|
|
done(results);
|
|
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
},
|
|
|
|
|
|
|
|
|
|
in(values, done) {
|
2016-10-07 17:27:48 +03:00
|
|
|
|
if (values.length === 0) {
|
|
|
|
|
return done([]);
|
|
|
|
|
}
|
2016-07-13 22:09:42 +03:00
|
|
|
|
const sortedValues = [].slice.call(values).sort();
|
|
|
|
|
const results = [];
|
|
|
|
|
return function (event) {
|
|
|
|
|
const cursor = event.target.result;
|
|
|
|
|
if (!cursor) {
|
|
|
|
|
done(results);
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
const { key, value } = cursor;
|
|
|
|
|
let i = 0;
|
|
|
|
|
while (key > sortedValues[i]) {
|
|
|
|
|
// The cursor has passed beyond this key. Check next.
|
|
|
|
|
++i;
|
|
|
|
|
if (i === sortedValues.length) {
|
|
|
|
|
done(results); // There is no next. Stop searching.
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
if (key === sortedValues[i]) {
|
|
|
|
|
results.push(value);
|
|
|
|
|
cursor.continue();
|
|
|
|
|
} else {
|
|
|
|
|
cursor.continue(sortedValues[i]);
|
|
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Extract from filters definition the first indexed field. Since indexes were
|
|
|
|
|
* created on single-columns, extracting a single one makes sense.
|
|
|
|
|
*
|
|
|
|
|
* @param {Object} filters The filters object.
|
|
|
|
|
* @return {String|undefined}
|
|
|
|
|
*/
|
|
|
|
|
function findIndexedField(filters) {
|
2016-11-16 03:38:53 +03:00
|
|
|
|
const filteredFields = Object.keys(filters);
|
2016-07-13 22:09:42 +03:00
|
|
|
|
const indexedFields = filteredFields.filter(field => {
|
|
|
|
|
return INDEXED_FIELDS.indexOf(field) !== -1;
|
|
|
|
|
});
|
|
|
|
|
return indexedFields[0];
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Creates an IDB request and attach it the appropriate cursor event handler to
|
|
|
|
|
* perform a list query.
|
|
|
|
|
*
|
|
|
|
|
* Multiple matching values are handled by passing an array.
|
|
|
|
|
*
|
|
|
|
|
* @param {IDBStore} store The IDB store.
|
|
|
|
|
* @param {String|undefined} indexField The indexed field to query, if any.
|
|
|
|
|
* @param {Any} value The value to filter, if any.
|
2016-10-07 17:27:48 +03:00
|
|
|
|
* @param {Object} filters More filters.
|
2016-07-13 22:09:42 +03:00
|
|
|
|
* @param {Function} done The operation completion handler.
|
|
|
|
|
* @return {IDBRequest}
|
|
|
|
|
*/
|
2016-10-07 17:27:48 +03:00
|
|
|
|
function createListRequest(store, indexField, value, filters, done) {
|
2016-07-13 22:09:42 +03:00
|
|
|
|
if (!indexField) {
|
|
|
|
|
// Get all records.
|
|
|
|
|
const request = store.openCursor();
|
2016-10-07 17:27:48 +03:00
|
|
|
|
request.onsuccess = cursorHandlers.all(filters, done);
|
2016-07-13 22:09:42 +03:00
|
|
|
|
return request;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// WHERE IN equivalent clause
|
|
|
|
|
if (Array.isArray(value)) {
|
|
|
|
|
const request = store.index(indexField).openCursor();
|
|
|
|
|
request.onsuccess = cursorHandlers.in(value, done);
|
|
|
|
|
return request;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// WHERE field = value clause
|
|
|
|
|
const request = store.index(indexField).openCursor(IDBKeyRange.only(value));
|
2016-10-07 17:27:48 +03:00
|
|
|
|
request.onsuccess = cursorHandlers.all(filters, done);
|
2016-07-13 22:09:42 +03:00
|
|
|
|
return request;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* IndexedDB adapter.
|
|
|
|
|
*
|
|
|
|
|
* This adapter doesn't support any options.
|
|
|
|
|
*/
|
|
|
|
|
class IDB extends _base2.default {
|
|
|
|
|
/**
|
|
|
|
|
* Constructor.
|
|
|
|
|
*
|
|
|
|
|
* @param {String} dbname The database nale.
|
|
|
|
|
*/
|
|
|
|
|
constructor(dbname) {
|
|
|
|
|
super();
|
|
|
|
|
this._db = null;
|
|
|
|
|
// public properties
|
|
|
|
|
/**
|
|
|
|
|
* The database name.
|
|
|
|
|
* @type {String}
|
|
|
|
|
*/
|
|
|
|
|
this.dbname = dbname;
|
|
|
|
|
}
|
|
|
|
|
|
2016-10-07 17:27:48 +03:00
|
|
|
|
_handleError(method, err) {
|
|
|
|
|
const error = new Error(method + "() " + err.message);
|
|
|
|
|
error.stack = err.stack;
|
|
|
|
|
throw error;
|
2016-07-13 22:09:42 +03:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Ensures a connection to the IndexedDB database has been opened.
|
|
|
|
|
*
|
|
|
|
|
* @override
|
|
|
|
|
* @return {Promise}
|
|
|
|
|
*/
|
|
|
|
|
open() {
|
|
|
|
|
if (this._db) {
|
2016-11-16 03:38:53 +03:00
|
|
|
|
return Promise.resolve(this);
|
2016-07-13 22:09:42 +03:00
|
|
|
|
}
|
2016-11-16 03:38:53 +03:00
|
|
|
|
return new Promise((resolve, reject) => {
|
2016-07-13 22:09:42 +03:00
|
|
|
|
const request = indexedDB.open(this.dbname, 1);
|
|
|
|
|
request.onupgradeneeded = event => {
|
|
|
|
|
// DB object
|
|
|
|
|
const db = event.target.result;
|
|
|
|
|
// Main collection store
|
|
|
|
|
const collStore = db.createObjectStore(this.dbname, {
|
|
|
|
|
keyPath: "id"
|
|
|
|
|
});
|
|
|
|
|
// Primary key (generated by IdSchema, UUID by default)
|
|
|
|
|
collStore.createIndex("id", "id", { unique: true });
|
|
|
|
|
// Local record status ("synced", "created", "updated", "deleted")
|
|
|
|
|
collStore.createIndex("_status", "_status");
|
|
|
|
|
// Last modified field
|
|
|
|
|
collStore.createIndex("last_modified", "last_modified");
|
|
|
|
|
|
|
|
|
|
// Metadata store
|
|
|
|
|
const metaStore = db.createObjectStore("__meta__", {
|
|
|
|
|
keyPath: "name"
|
|
|
|
|
});
|
|
|
|
|
metaStore.createIndex("name", "name", { unique: true });
|
|
|
|
|
};
|
|
|
|
|
request.onerror = event => reject(event.target.error);
|
|
|
|
|
request.onsuccess = event => {
|
|
|
|
|
this._db = event.target.result;
|
|
|
|
|
resolve(this);
|
|
|
|
|
};
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Closes current connection to the database.
|
|
|
|
|
*
|
|
|
|
|
* @override
|
|
|
|
|
* @return {Promise}
|
|
|
|
|
*/
|
|
|
|
|
close() {
|
|
|
|
|
if (this._db) {
|
|
|
|
|
this._db.close(); // indexedDB.close is synchronous
|
|
|
|
|
this._db = null;
|
|
|
|
|
}
|
2017-01-18 16:53:52 +03:00
|
|
|
|
return Promise.resolve();
|
2016-07-13 22:09:42 +03:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Returns a transaction and a store objects for this collection.
|
|
|
|
|
*
|
|
|
|
|
* To determine if a transaction has completed successfully, we should rather
|
|
|
|
|
* listen to the transaction’s complete event rather than the IDBObjectStore
|
|
|
|
|
* request’s success event, because the transaction may still fail after the
|
|
|
|
|
* success event fires.
|
|
|
|
|
*
|
|
|
|
|
* @param {String} mode Transaction mode ("readwrite" or undefined)
|
|
|
|
|
* @param {String|null} name Store name (defaults to coll name)
|
|
|
|
|
* @return {Object}
|
|
|
|
|
*/
|
|
|
|
|
prepare(mode = undefined, name = null) {
|
|
|
|
|
const storeName = name || this.dbname;
|
|
|
|
|
// On Safari, calling IDBDatabase.transaction with mode == undefined raises
|
|
|
|
|
// a TypeError.
|
|
|
|
|
const transaction = mode ? this._db.transaction([storeName], mode) : this._db.transaction([storeName]);
|
|
|
|
|
const store = transaction.objectStore(storeName);
|
|
|
|
|
return { transaction, store };
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Deletes every records in the current collection.
|
|
|
|
|
*
|
|
|
|
|
* @override
|
|
|
|
|
* @return {Promise}
|
|
|
|
|
*/
|
|
|
|
|
clear() {
|
2016-10-07 17:27:48 +03:00
|
|
|
|
var _this = this;
|
|
|
|
|
|
2016-11-16 03:38:53 +03:00
|
|
|
|
return _asyncToGenerator(function* () {
|
2016-10-07 17:27:48 +03:00
|
|
|
|
try {
|
|
|
|
|
yield _this.open();
|
2016-11-16 03:38:53 +03:00
|
|
|
|
return new Promise(function (resolve, reject) {
|
2016-10-07 17:27:48 +03:00
|
|
|
|
const { transaction, store } = _this.prepare("readwrite");
|
|
|
|
|
store.clear();
|
|
|
|
|
transaction.onerror = function (event) {
|
|
|
|
|
return reject(new Error(event.target.error));
|
|
|
|
|
};
|
|
|
|
|
transaction.oncomplete = function () {
|
|
|
|
|
return resolve();
|
|
|
|
|
};
|
|
|
|
|
});
|
|
|
|
|
} catch (e) {
|
|
|
|
|
_this._handleError("clear", e);
|
|
|
|
|
}
|
|
|
|
|
})();
|
2016-07-13 22:09:42 +03:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Executes the set of synchronous CRUD operations described in the provided
|
|
|
|
|
* callback within an IndexedDB transaction, for current db store.
|
|
|
|
|
*
|
|
|
|
|
* The callback will be provided an object exposing the following synchronous
|
|
|
|
|
* CRUD operation methods: get, create, update, delete.
|
|
|
|
|
*
|
|
|
|
|
* Important note: because limitations in IndexedDB implementations, no
|
|
|
|
|
* asynchronous code should be performed within the provided callback; the
|
|
|
|
|
* promise will therefore be rejected if the callback returns a Promise.
|
|
|
|
|
*
|
|
|
|
|
* Options:
|
|
|
|
|
* - {Array} preload: The list of record IDs to fetch and make available to
|
|
|
|
|
* the transaction object get() method (default: [])
|
|
|
|
|
*
|
|
|
|
|
* @example
|
|
|
|
|
* const db = new IDB("example");
|
|
|
|
|
* db.execute(transaction => {
|
|
|
|
|
* transaction.create({id: 1, title: "foo"});
|
|
|
|
|
* transaction.update({id: 2, title: "bar"});
|
|
|
|
|
* transaction.delete(3);
|
|
|
|
|
* return "foo";
|
|
|
|
|
* })
|
|
|
|
|
* .catch(console.error.bind(console));
|
|
|
|
|
* .then(console.log.bind(console)); // => "foo"
|
|
|
|
|
*
|
|
|
|
|
* @param {Function} callback The operation description callback.
|
|
|
|
|
* @param {Object} options The options object.
|
|
|
|
|
* @return {Promise}
|
|
|
|
|
*/
|
|
|
|
|
execute(callback, options = { preload: [] }) {
|
2016-10-07 17:27:48 +03:00
|
|
|
|
var _this2 = this;
|
|
|
|
|
|
2016-11-16 03:38:53 +03:00
|
|
|
|
return _asyncToGenerator(function* () {
|
2016-10-07 17:27:48 +03:00
|
|
|
|
// Transactions in IndexedDB are autocommited when a callback does not
|
|
|
|
|
// perform any additional operation.
|
|
|
|
|
// The way Promises are implemented in Firefox (see https://bugzilla.mozilla.org/show_bug.cgi?id=1193394)
|
|
|
|
|
// prevents using within an opened transaction.
|
|
|
|
|
// To avoid managing asynchronocity in the specified `callback`, we preload
|
|
|
|
|
// a list of record in order to execute the `callback` synchronously.
|
|
|
|
|
// See also:
|
|
|
|
|
// - http://stackoverflow.com/a/28388805/330911
|
|
|
|
|
// - http://stackoverflow.com/a/10405196
|
|
|
|
|
// - https://jakearchibald.com/2015/tasks-microtasks-queues-and-schedules/
|
|
|
|
|
yield _this2.open();
|
2016-11-16 03:38:53 +03:00
|
|
|
|
return new Promise(function (resolve, reject) {
|
2016-10-07 17:27:48 +03:00
|
|
|
|
// Start transaction.
|
|
|
|
|
const { transaction, store } = _this2.prepare("readwrite");
|
|
|
|
|
// Preload specified records using index.
|
|
|
|
|
const ids = options.preload;
|
|
|
|
|
store.index("id").openCursor().onsuccess = cursorHandlers.in(ids, function (records) {
|
|
|
|
|
// Store obtained records by id.
|
|
|
|
|
const preloaded = records.reduce(function (acc, record) {
|
|
|
|
|
acc[record.id] = record;
|
|
|
|
|
return acc;
|
|
|
|
|
}, {});
|
|
|
|
|
// Expose a consistent API for every adapter instead of raw store methods.
|
|
|
|
|
const proxy = transactionProxy(store, preloaded);
|
|
|
|
|
// The callback is executed synchronously within the same transaction.
|
|
|
|
|
let result;
|
|
|
|
|
try {
|
|
|
|
|
result = callback(proxy);
|
|
|
|
|
} catch (e) {
|
|
|
|
|
transaction.abort();
|
|
|
|
|
reject(e);
|
|
|
|
|
}
|
2016-11-16 03:38:53 +03:00
|
|
|
|
if (result instanceof Promise) {
|
2016-10-07 17:27:48 +03:00
|
|
|
|
// XXX: investigate how to provide documentation details in error.
|
|
|
|
|
reject(new Error("execute() callback should not return a Promise."));
|
|
|
|
|
}
|
|
|
|
|
// XXX unsure if we should manually abort the transaction on error
|
|
|
|
|
transaction.onerror = function (event) {
|
|
|
|
|
return reject(new Error(event.target.error));
|
|
|
|
|
};
|
|
|
|
|
transaction.oncomplete = function (event) {
|
|
|
|
|
return resolve(result);
|
|
|
|
|
};
|
|
|
|
|
});
|
2016-07-13 22:09:42 +03:00
|
|
|
|
});
|
2016-10-07 17:27:48 +03:00
|
|
|
|
})();
|
2016-07-13 22:09:42 +03:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Retrieve a record by its primary key from the IndexedDB database.
|
|
|
|
|
*
|
|
|
|
|
* @override
|
|
|
|
|
* @param {String} id The record id.
|
|
|
|
|
* @return {Promise}
|
|
|
|
|
*/
|
|
|
|
|
get(id) {
|
2016-10-07 17:27:48 +03:00
|
|
|
|
var _this3 = this;
|
|
|
|
|
|
2016-11-16 03:38:53 +03:00
|
|
|
|
return _asyncToGenerator(function* () {
|
2016-10-07 17:27:48 +03:00
|
|
|
|
try {
|
|
|
|
|
yield _this3.open();
|
2016-11-16 03:38:53 +03:00
|
|
|
|
return new Promise(function (resolve, reject) {
|
2016-10-07 17:27:48 +03:00
|
|
|
|
const { transaction, store } = _this3.prepare();
|
|
|
|
|
const request = store.get(id);
|
|
|
|
|
transaction.onerror = function (event) {
|
|
|
|
|
return reject(new Error(event.target.error));
|
|
|
|
|
};
|
|
|
|
|
transaction.oncomplete = function () {
|
|
|
|
|
return resolve(request.result);
|
|
|
|
|
};
|
|
|
|
|
});
|
|
|
|
|
} catch (e) {
|
|
|
|
|
_this3._handleError("get", e);
|
|
|
|
|
}
|
|
|
|
|
})();
|
2016-07-13 22:09:42 +03:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Lists all records from the IndexedDB database.
|
|
|
|
|
*
|
|
|
|
|
* @override
|
|
|
|
|
* @return {Promise}
|
|
|
|
|
*/
|
|
|
|
|
list(params = { filters: {} }) {
|
2016-10-07 17:27:48 +03:00
|
|
|
|
var _this4 = this;
|
|
|
|
|
|
2016-11-16 03:38:53 +03:00
|
|
|
|
return _asyncToGenerator(function* () {
|
2016-10-07 17:27:48 +03:00
|
|
|
|
const { filters } = params;
|
|
|
|
|
const indexField = findIndexedField(filters);
|
|
|
|
|
const value = filters[indexField];
|
|
|
|
|
try {
|
|
|
|
|
yield _this4.open();
|
2016-11-16 03:38:53 +03:00
|
|
|
|
const results = yield new Promise(function (resolve, reject) {
|
2016-10-07 17:27:48 +03:00
|
|
|
|
let results = [];
|
|
|
|
|
// If `indexField` was used already, don't filter again.
|
|
|
|
|
const remainingFilters = (0, _utils.omitKeys)(filters, indexField);
|
|
|
|
|
|
|
|
|
|
const { transaction, store } = _this4.prepare();
|
|
|
|
|
createListRequest(store, indexField, value, remainingFilters, function (_results) {
|
|
|
|
|
// we have received all requested records, parking them within
|
|
|
|
|
// current scope
|
|
|
|
|
results = _results;
|
|
|
|
|
});
|
|
|
|
|
transaction.onerror = function (event) {
|
|
|
|
|
return reject(new Error(event.target.error));
|
|
|
|
|
};
|
|
|
|
|
transaction.oncomplete = function (event) {
|
|
|
|
|
return resolve(results);
|
|
|
|
|
};
|
2016-07-13 22:09:42 +03:00
|
|
|
|
});
|
2016-10-07 17:27:48 +03:00
|
|
|
|
|
|
|
|
|
// The resulting list of records is sorted.
|
|
|
|
|
// XXX: with some efforts, this could be fully implemented using IDB API.
|
|
|
|
|
return params.order ? (0, _utils.sortObjects)(params.order, results) : results;
|
|
|
|
|
} catch (e) {
|
|
|
|
|
_this4._handleError("list", e);
|
|
|
|
|
}
|
|
|
|
|
})();
|
2016-07-13 22:09:42 +03:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Store the lastModified value into metadata store.
|
|
|
|
|
*
|
|
|
|
|
* @override
|
|
|
|
|
* @param {Number} lastModified
|
|
|
|
|
* @return {Promise}
|
|
|
|
|
*/
|
|
|
|
|
saveLastModified(lastModified) {
|
2016-10-07 17:27:48 +03:00
|
|
|
|
var _this5 = this;
|
|
|
|
|
|
2016-11-16 03:38:53 +03:00
|
|
|
|
return _asyncToGenerator(function* () {
|
2016-10-07 17:27:48 +03:00
|
|
|
|
const value = parseInt(lastModified, 10) || null;
|
|
|
|
|
yield _this5.open();
|
2016-11-16 03:38:53 +03:00
|
|
|
|
return new Promise(function (resolve, reject) {
|
2016-10-07 17:27:48 +03:00
|
|
|
|
const { transaction, store } = _this5.prepare("readwrite", "__meta__");
|
2016-07-13 22:09:42 +03:00
|
|
|
|
store.put({ name: "lastModified", value: value });
|
2016-10-07 17:27:48 +03:00
|
|
|
|
transaction.onerror = function (event) {
|
|
|
|
|
return reject(event.target.error);
|
|
|
|
|
};
|
|
|
|
|
transaction.oncomplete = function (event) {
|
|
|
|
|
return resolve(value);
|
|
|
|
|
};
|
2016-07-13 22:09:42 +03:00
|
|
|
|
});
|
2016-10-07 17:27:48 +03:00
|
|
|
|
})();
|
2016-07-13 22:09:42 +03:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Retrieve saved lastModified value.
|
|
|
|
|
*
|
|
|
|
|
* @override
|
|
|
|
|
* @return {Promise}
|
|
|
|
|
*/
|
|
|
|
|
getLastModified() {
|
2016-10-07 17:27:48 +03:00
|
|
|
|
var _this6 = this;
|
|
|
|
|
|
2016-11-16 03:38:53 +03:00
|
|
|
|
return _asyncToGenerator(function* () {
|
2016-10-07 17:27:48 +03:00
|
|
|
|
yield _this6.open();
|
2016-11-16 03:38:53 +03:00
|
|
|
|
return new Promise(function (resolve, reject) {
|
2016-10-07 17:27:48 +03:00
|
|
|
|
const { transaction, store } = _this6.prepare(undefined, "__meta__");
|
2016-07-13 22:09:42 +03:00
|
|
|
|
const request = store.get("lastModified");
|
2016-10-07 17:27:48 +03:00
|
|
|
|
transaction.onerror = function (event) {
|
|
|
|
|
return reject(event.target.error);
|
|
|
|
|
};
|
|
|
|
|
transaction.oncomplete = function (event) {
|
2016-07-13 22:09:42 +03:00
|
|
|
|
resolve(request.result && request.result.value || null);
|
|
|
|
|
};
|
|
|
|
|
});
|
2016-10-07 17:27:48 +03:00
|
|
|
|
})();
|
2016-07-13 22:09:42 +03:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Load a dump of records exported from a server.
|
|
|
|
|
*
|
|
|
|
|
* @abstract
|
|
|
|
|
* @return {Promise}
|
|
|
|
|
*/
|
|
|
|
|
loadDump(records) {
|
2016-10-07 17:27:48 +03:00
|
|
|
|
var _this7 = this;
|
|
|
|
|
|
2016-11-16 03:38:53 +03:00
|
|
|
|
return _asyncToGenerator(function* () {
|
2016-10-07 17:27:48 +03:00
|
|
|
|
try {
|
|
|
|
|
yield _this7.execute(function (transaction) {
|
|
|
|
|
records.forEach(function (record) {
|
|
|
|
|
return transaction.update(record);
|
|
|
|
|
});
|
|
|
|
|
});
|
|
|
|
|
const previousLastModified = yield _this7.getLastModified();
|
|
|
|
|
const lastModified = Math.max(...records.map(function (record) {
|
|
|
|
|
return record.last_modified;
|
|
|
|
|
}));
|
|
|
|
|
if (lastModified > previousLastModified) {
|
|
|
|
|
yield _this7.saveLastModified(lastModified);
|
|
|
|
|
}
|
|
|
|
|
return records;
|
|
|
|
|
} catch (e) {
|
|
|
|
|
_this7._handleError("loadDump", e);
|
2016-07-13 22:09:42 +03:00
|
|
|
|
}
|
2016-10-07 17:27:48 +03:00
|
|
|
|
})();
|
2016-07-13 22:09:42 +03:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
exports.default = IDB; /**
|
|
|
|
|
* IDB transaction proxy.
|
|
|
|
|
*
|
|
|
|
|
* @param {IDBStore} store The IndexedDB database store.
|
|
|
|
|
* @param {Array} preloaded The list of records to make available to
|
|
|
|
|
* get() (default: []).
|
|
|
|
|
* @return {Object}
|
|
|
|
|
*/
|
|
|
|
|
|
|
|
|
|
function transactionProxy(store, preloaded = []) {
|
|
|
|
|
return {
|
|
|
|
|
create(record) {
|
|
|
|
|
store.add(record);
|
|
|
|
|
},
|
|
|
|
|
|
|
|
|
|
update(record) {
|
|
|
|
|
store.put(record);
|
|
|
|
|
},
|
|
|
|
|
|
|
|
|
|
delete(id) {
|
|
|
|
|
store.delete(id);
|
|
|
|
|
},
|
|
|
|
|
|
|
|
|
|
get(id) {
|
|
|
|
|
return preloaded[id];
|
|
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
}
|
|
|
|
|
|
2016-11-16 03:38:53 +03:00
|
|
|
|
},{"../utils":7,"./base.js":5}],5:[function(require,module,exports){
|
2016-04-15 02:07:31 +03:00
|
|
|
|
"use strict";
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Base db adapter.
|
|
|
|
|
*
|
|
|
|
|
* @abstract
|
|
|
|
|
*/
|
|
|
|
|
|
|
|
|
|
Object.defineProperty(exports, "__esModule", {
|
|
|
|
|
value: true
|
|
|
|
|
});
|
|
|
|
|
class BaseAdapter {
|
|
|
|
|
/**
|
|
|
|
|
* Deletes every records present in the database.
|
|
|
|
|
*
|
|
|
|
|
* @abstract
|
|
|
|
|
* @return {Promise}
|
|
|
|
|
*/
|
|
|
|
|
clear() {
|
|
|
|
|
throw new Error("Not Implemented.");
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Executes a batch of operations within a single transaction.
|
|
|
|
|
*
|
|
|
|
|
* @abstract
|
|
|
|
|
* @param {Function} callback The operation callback.
|
|
|
|
|
* @param {Object} options The options object.
|
|
|
|
|
* @return {Promise}
|
|
|
|
|
*/
|
|
|
|
|
execute(callback, options = { preload: [] }) {
|
|
|
|
|
throw new Error("Not Implemented.");
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Retrieve a record by its primary key from the database.
|
|
|
|
|
*
|
|
|
|
|
* @abstract
|
|
|
|
|
* @param {String} id The record id.
|
|
|
|
|
* @return {Promise}
|
|
|
|
|
*/
|
|
|
|
|
get(id) {
|
|
|
|
|
throw new Error("Not Implemented.");
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Lists all records from the database.
|
|
|
|
|
*
|
|
|
|
|
* @abstract
|
|
|
|
|
* @param {Object} params The filters and order to apply to the results.
|
|
|
|
|
* @return {Promise}
|
|
|
|
|
*/
|
|
|
|
|
list(params = { filters: {}, order: "" }) {
|
|
|
|
|
throw new Error("Not Implemented.");
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Store the lastModified value.
|
|
|
|
|
*
|
|
|
|
|
* @abstract
|
|
|
|
|
* @param {Number} lastModified
|
|
|
|
|
* @return {Promise}
|
|
|
|
|
*/
|
|
|
|
|
saveLastModified(lastModified) {
|
|
|
|
|
throw new Error("Not Implemented.");
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Retrieve saved lastModified value.
|
|
|
|
|
*
|
|
|
|
|
* @abstract
|
|
|
|
|
* @return {Promise}
|
|
|
|
|
*/
|
|
|
|
|
getLastModified() {
|
|
|
|
|
throw new Error("Not Implemented.");
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Load a dump of records exported from a server.
|
|
|
|
|
*
|
|
|
|
|
* @abstract
|
|
|
|
|
* @return {Promise}
|
|
|
|
|
*/
|
|
|
|
|
loadDump(records) {
|
|
|
|
|
throw new Error("Not Implemented.");
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
exports.default = BaseAdapter;
|
|
|
|
|
|
2016-11-16 03:38:53 +03:00
|
|
|
|
},{}],6:[function(require,module,exports){
|
2016-04-15 02:07:31 +03:00
|
|
|
|
"use strict";
|
|
|
|
|
|
|
|
|
|
Object.defineProperty(exports, "__esModule", {
|
|
|
|
|
value: true
|
|
|
|
|
});
|
2016-07-13 22:09:42 +03:00
|
|
|
|
exports.CollectionTransaction = exports.SyncResultObject = undefined;
|
|
|
|
|
|
2016-11-16 03:38:53 +03:00
|
|
|
|
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
|
2016-07-13 22:09:42 +03:00
|
|
|
|
|
|
|
|
|
exports.recordsEqual = recordsEqual;
|
2016-04-15 02:07:31 +03:00
|
|
|
|
|
|
|
|
|
var _base = require("./adapters/base");
|
|
|
|
|
|
|
|
|
|
var _base2 = _interopRequireDefault(_base);
|
|
|
|
|
|
2016-07-13 22:09:42 +03:00
|
|
|
|
var _IDB = require("./adapters/IDB");
|
|
|
|
|
|
|
|
|
|
var _IDB2 = _interopRequireDefault(_IDB);
|
|
|
|
|
|
2016-04-15 02:07:31 +03:00
|
|
|
|
var _utils = require("./utils");
|
|
|
|
|
|
|
|
|
|
var _uuid = require("uuid");
|
|
|
|
|
|
|
|
|
|
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
|
|
|
|
|
2016-11-16 03:38:53 +03:00
|
|
|
|
function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; }
|
|
|
|
|
|
2016-07-13 22:09:42 +03:00
|
|
|
|
const RECORD_FIELDS_TO_CLEAN = ["_status"];
|
2016-04-15 02:07:31 +03:00
|
|
|
|
const AVAILABLE_HOOKS = ["incoming-changes"];
|
|
|
|
|
|
|
|
|
|
/**
|
2016-07-13 22:09:42 +03:00
|
|
|
|
* Compare two records omitting local fields and synchronization
|
|
|
|
|
* attributes (like _status and last_modified)
|
|
|
|
|
* @param {Object} a A record to compare.
|
|
|
|
|
* @param {Object} b A record to compare.
|
|
|
|
|
* @return {boolean}
|
2016-04-15 02:07:31 +03:00
|
|
|
|
*/
|
2016-07-13 22:09:42 +03:00
|
|
|
|
function recordsEqual(a, b, localFields = []) {
|
|
|
|
|
const fieldsToClean = RECORD_FIELDS_TO_CLEAN.concat(["last_modified"]).concat(localFields);
|
|
|
|
|
const cleanLocal = r => (0, _utils.omitKeys)(r, fieldsToClean);
|
|
|
|
|
return (0, _utils.deepEqual)(cleanLocal(a), cleanLocal(b));
|
2016-04-15 02:07:31 +03:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Synchronization result object.
|
|
|
|
|
*/
|
|
|
|
|
class SyncResultObject {
|
|
|
|
|
/**
|
|
|
|
|
* Object default values.
|
|
|
|
|
* @type {Object}
|
|
|
|
|
*/
|
|
|
|
|
static get defaults() {
|
|
|
|
|
return {
|
|
|
|
|
ok: true,
|
|
|
|
|
lastModified: null,
|
|
|
|
|
errors: [],
|
|
|
|
|
created: [],
|
|
|
|
|
updated: [],
|
|
|
|
|
deleted: [],
|
|
|
|
|
published: [],
|
|
|
|
|
conflicts: [],
|
|
|
|
|
skipped: [],
|
|
|
|
|
resolved: []
|
|
|
|
|
};
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Public constructor.
|
|
|
|
|
*/
|
|
|
|
|
constructor() {
|
|
|
|
|
/**
|
|
|
|
|
* Current synchronization result status; becomes `false` when conflicts or
|
|
|
|
|
* errors are registered.
|
|
|
|
|
* @type {Boolean}
|
|
|
|
|
*/
|
|
|
|
|
this.ok = true;
|
2016-11-16 03:38:53 +03:00
|
|
|
|
Object.assign(this, SyncResultObject.defaults);
|
2016-04-15 02:07:31 +03:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Adds entries for a given result type.
|
|
|
|
|
*
|
|
|
|
|
* @param {String} type The result type.
|
|
|
|
|
* @param {Array} entries The result entries.
|
|
|
|
|
* @return {SyncResultObject}
|
|
|
|
|
*/
|
|
|
|
|
add(type, entries) {
|
|
|
|
|
if (!Array.isArray(this[type])) {
|
|
|
|
|
return;
|
|
|
|
|
}
|
2016-10-07 17:27:48 +03:00
|
|
|
|
// Deduplicate entries by id. If the values don't have `id` attribute, just
|
|
|
|
|
// keep all.
|
|
|
|
|
const deduplicated = this[type].concat(entries).reduce((acc, cur) => {
|
|
|
|
|
const existing = acc.filter(r => cur.id && r.id ? cur.id != r.id : true);
|
|
|
|
|
return existing.concat(cur);
|
|
|
|
|
}, []);
|
|
|
|
|
this[type] = deduplicated;
|
2016-04-15 02:07:31 +03:00
|
|
|
|
this.ok = this.errors.length + this.conflicts.length === 0;
|
|
|
|
|
return this;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Reinitializes result entries for a given result type.
|
|
|
|
|
*
|
|
|
|
|
* @param {String} type The result type.
|
|
|
|
|
* @return {SyncResultObject}
|
|
|
|
|
*/
|
|
|
|
|
reset(type) {
|
|
|
|
|
this[type] = SyncResultObject.defaults[type];
|
|
|
|
|
this.ok = this.errors.length + this.conflicts.length === 0;
|
|
|
|
|
return this;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
exports.SyncResultObject = SyncResultObject;
|
|
|
|
|
function createUUIDSchema() {
|
|
|
|
|
return {
|
|
|
|
|
generate() {
|
|
|
|
|
return (0, _uuid.v4)();
|
|
|
|
|
},
|
|
|
|
|
|
|
|
|
|
validate(id) {
|
|
|
|
|
return (0, _utils.isUUID)(id);
|
|
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function markStatus(record, status) {
|
2016-11-16 03:38:53 +03:00
|
|
|
|
return _extends({}, record, { _status: status });
|
2016-04-15 02:07:31 +03:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function markDeleted(record) {
|
|
|
|
|
return markStatus(record, "deleted");
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function markSynced(record) {
|
|
|
|
|
return markStatus(record, "synced");
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Import a remote change into the local database.
|
|
|
|
|
*
|
|
|
|
|
* @param {IDBTransactionProxy} transaction The transaction handler.
|
|
|
|
|
* @param {Object} remote The remote change object to import.
|
2016-07-13 22:09:42 +03:00
|
|
|
|
* @param {Array<String>} localFields The list of fields that remain local.
|
2016-04-15 02:07:31 +03:00
|
|
|
|
* @return {Object}
|
|
|
|
|
*/
|
2016-07-13 22:09:42 +03:00
|
|
|
|
function importChange(transaction, remote, localFields) {
|
2016-04-15 02:07:31 +03:00
|
|
|
|
const local = transaction.get(remote.id);
|
|
|
|
|
if (!local) {
|
|
|
|
|
// Not found locally but remote change is marked as deleted; skip to
|
|
|
|
|
// avoid recreation.
|
|
|
|
|
if (remote.deleted) {
|
|
|
|
|
return { type: "skipped", data: remote };
|
|
|
|
|
}
|
|
|
|
|
const synced = markSynced(remote);
|
|
|
|
|
transaction.create(synced);
|
|
|
|
|
return { type: "created", data: synced };
|
|
|
|
|
}
|
2016-07-13 22:09:42 +03:00
|
|
|
|
// Compare local and remote, ignoring local fields.
|
|
|
|
|
const isIdentical = recordsEqual(local, remote, localFields);
|
|
|
|
|
// Apply remote changes on local record.
|
2016-11-16 03:38:53 +03:00
|
|
|
|
const synced = _extends({}, local, markSynced(remote));
|
2016-07-13 22:09:42 +03:00
|
|
|
|
// Detect or ignore conflicts if record has also been modified locally.
|
2016-04-15 02:07:31 +03:00
|
|
|
|
if (local._status !== "synced") {
|
|
|
|
|
// Locally deleted, unsynced: scheduled for remote deletion.
|
|
|
|
|
if (local._status === "deleted") {
|
|
|
|
|
return { type: "skipped", data: local };
|
|
|
|
|
}
|
2016-07-13 22:09:42 +03:00
|
|
|
|
if (isIdentical) {
|
2016-04-15 02:07:31 +03:00
|
|
|
|
// If records are identical, import anyway, so we bump the
|
|
|
|
|
// local last_modified value from the server and set record
|
|
|
|
|
// status to "synced".
|
|
|
|
|
transaction.update(synced);
|
2016-07-13 22:09:42 +03:00
|
|
|
|
return { type: "updated", data: { old: local, new: synced } };
|
|
|
|
|
}
|
|
|
|
|
if (local.last_modified !== undefined && local.last_modified === remote.last_modified) {
|
|
|
|
|
// If our local version has the same last_modified as the remote
|
|
|
|
|
// one, this represents an object that corresponds to a resolved
|
|
|
|
|
// conflict. Our local version represents the final output, so
|
|
|
|
|
// we keep that one. (No transaction operation to do.)
|
|
|
|
|
// But if our last_modified is undefined,
|
|
|
|
|
// that means we've created the same object locally as one on
|
|
|
|
|
// the server, which *must* be a conflict.
|
|
|
|
|
return { type: "void" };
|
2016-04-15 02:07:31 +03:00
|
|
|
|
}
|
|
|
|
|
return {
|
|
|
|
|
type: "conflicts",
|
|
|
|
|
data: { type: "incoming", local: local, remote: remote }
|
|
|
|
|
};
|
|
|
|
|
}
|
2016-07-13 22:09:42 +03:00
|
|
|
|
// Local record was synced.
|
2016-04-15 02:07:31 +03:00
|
|
|
|
if (remote.deleted) {
|
|
|
|
|
transaction.delete(remote.id);
|
2016-07-13 22:09:42 +03:00
|
|
|
|
return { type: "deleted", data: local };
|
2016-04-15 02:07:31 +03:00
|
|
|
|
}
|
2016-07-13 22:09:42 +03:00
|
|
|
|
// Import locally.
|
2016-04-15 02:07:31 +03:00
|
|
|
|
transaction.update(synced);
|
2016-07-13 22:09:42 +03:00
|
|
|
|
// if identical, simply exclude it from all SyncResultObject lists
|
|
|
|
|
const type = isIdentical ? "void" : "updated";
|
|
|
|
|
return { type, data: { old: local, new: synced } };
|
2016-04-15 02:07:31 +03:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Abstracts a collection of records stored in the local database, providing
|
|
|
|
|
* CRUD operations and synchronization helpers.
|
|
|
|
|
*/
|
|
|
|
|
class Collection {
|
|
|
|
|
/**
|
|
|
|
|
* Constructor.
|
|
|
|
|
*
|
|
|
|
|
* Options:
|
|
|
|
|
* - `{BaseAdapter} adapter` The DB adapter (default: `IDB`)
|
|
|
|
|
* - `{String} dbPrefix` The DB name prefix (default: `""`)
|
|
|
|
|
*
|
|
|
|
|
* @param {String} bucket The bucket identifier.
|
|
|
|
|
* @param {String} name The collection name.
|
|
|
|
|
* @param {Api} api The Api instance.
|
|
|
|
|
* @param {Object} options The options object.
|
|
|
|
|
*/
|
|
|
|
|
constructor(bucket, name, api, options = {}) {
|
|
|
|
|
this._bucket = bucket;
|
|
|
|
|
this._name = name;
|
|
|
|
|
this._lastModified = null;
|
|
|
|
|
|
2016-07-13 22:09:42 +03:00
|
|
|
|
const DBAdapter = options.adapter || _IDB2.default;
|
2016-04-15 02:07:31 +03:00
|
|
|
|
if (!DBAdapter) {
|
|
|
|
|
throw new Error("No adapter provided");
|
|
|
|
|
}
|
|
|
|
|
const dbPrefix = options.dbPrefix || "";
|
2017-01-28 03:23:05 +03:00
|
|
|
|
const db = new DBAdapter(`${dbPrefix}${bucket}/${name}`, options.adapterOptions);
|
2016-04-15 02:07:31 +03:00
|
|
|
|
if (!(db instanceof _base2.default)) {
|
|
|
|
|
throw new Error("Unsupported adapter.");
|
|
|
|
|
}
|
|
|
|
|
// public properties
|
|
|
|
|
/**
|
|
|
|
|
* The db adapter instance
|
|
|
|
|
* @type {BaseAdapter}
|
|
|
|
|
*/
|
|
|
|
|
this.db = db;
|
|
|
|
|
/**
|
|
|
|
|
* The Api instance.
|
|
|
|
|
* @type {KintoClient}
|
|
|
|
|
*/
|
|
|
|
|
this.api = api;
|
|
|
|
|
/**
|
|
|
|
|
* The event emitter instance.
|
|
|
|
|
* @type {EventEmitter}
|
|
|
|
|
*/
|
|
|
|
|
this.events = options.events;
|
|
|
|
|
/**
|
|
|
|
|
* The IdSchema instance.
|
|
|
|
|
* @type {Object}
|
|
|
|
|
*/
|
|
|
|
|
this.idSchema = this._validateIdSchema(options.idSchema);
|
|
|
|
|
/**
|
|
|
|
|
* The list of remote transformers.
|
|
|
|
|
* @type {Array}
|
|
|
|
|
*/
|
|
|
|
|
this.remoteTransformers = this._validateRemoteTransformers(options.remoteTransformers);
|
|
|
|
|
/**
|
|
|
|
|
* The list of hooks.
|
|
|
|
|
* @type {Object}
|
|
|
|
|
*/
|
|
|
|
|
this.hooks = this._validateHooks(options.hooks);
|
2016-07-13 22:09:42 +03:00
|
|
|
|
/**
|
|
|
|
|
* The list of fields names that will remain local.
|
|
|
|
|
* @type {Array}
|
|
|
|
|
*/
|
|
|
|
|
this.localFields = options.localFields || [];
|
2016-04-15 02:07:31 +03:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* The collection name.
|
|
|
|
|
* @type {String}
|
|
|
|
|
*/
|
|
|
|
|
get name() {
|
|
|
|
|
return this._name;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* The bucket name.
|
|
|
|
|
* @type {String}
|
|
|
|
|
*/
|
|
|
|
|
get bucket() {
|
|
|
|
|
return this._bucket;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* The last modified timestamp.
|
|
|
|
|
* @type {Number}
|
|
|
|
|
*/
|
|
|
|
|
get lastModified() {
|
|
|
|
|
return this._lastModified;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Synchronization strategies. Available strategies are:
|
|
|
|
|
*
|
|
|
|
|
* - `MANUAL`: Conflicts will be reported in a dedicated array.
|
|
|
|
|
* - `SERVER_WINS`: Conflicts are resolved using remote data.
|
|
|
|
|
* - `CLIENT_WINS`: Conflicts are resolved using local data.
|
|
|
|
|
*
|
|
|
|
|
* @type {Object}
|
|
|
|
|
*/
|
|
|
|
|
static get strategy() {
|
|
|
|
|
return {
|
|
|
|
|
CLIENT_WINS: "client_wins",
|
|
|
|
|
SERVER_WINS: "server_wins",
|
|
|
|
|
MANUAL: "manual"
|
|
|
|
|
};
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Validates an idSchema.
|
|
|
|
|
*
|
|
|
|
|
* @param {Object|undefined} idSchema
|
|
|
|
|
* @return {Object}
|
|
|
|
|
*/
|
|
|
|
|
_validateIdSchema(idSchema) {
|
|
|
|
|
if (typeof idSchema === "undefined") {
|
|
|
|
|
return createUUIDSchema();
|
|
|
|
|
}
|
|
|
|
|
if (typeof idSchema !== "object") {
|
|
|
|
|
throw new Error("idSchema must be an object.");
|
|
|
|
|
} else if (typeof idSchema.generate !== "function") {
|
|
|
|
|
throw new Error("idSchema must provide a generate function.");
|
|
|
|
|
} else if (typeof idSchema.validate !== "function") {
|
|
|
|
|
throw new Error("idSchema must provide a validate function.");
|
|
|
|
|
}
|
|
|
|
|
return idSchema;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Validates a list of remote transformers.
|
|
|
|
|
*
|
|
|
|
|
* @param {Array|undefined} remoteTransformers
|
|
|
|
|
* @return {Array}
|
|
|
|
|
*/
|
|
|
|
|
_validateRemoteTransformers(remoteTransformers) {
|
|
|
|
|
if (typeof remoteTransformers === "undefined") {
|
|
|
|
|
return [];
|
|
|
|
|
}
|
|
|
|
|
if (!Array.isArray(remoteTransformers)) {
|
|
|
|
|
throw new Error("remoteTransformers should be an array.");
|
|
|
|
|
}
|
|
|
|
|
return remoteTransformers.map(transformer => {
|
|
|
|
|
if (typeof transformer !== "object") {
|
|
|
|
|
throw new Error("A transformer must be an object.");
|
|
|
|
|
} else if (typeof transformer.encode !== "function") {
|
|
|
|
|
throw new Error("A transformer must provide an encode function.");
|
|
|
|
|
} else if (typeof transformer.decode !== "function") {
|
|
|
|
|
throw new Error("A transformer must provide a decode function.");
|
|
|
|
|
}
|
|
|
|
|
return transformer;
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Validate the passed hook is correct.
|
|
|
|
|
*
|
|
|
|
|
* @param {Array|undefined} hook.
|
|
|
|
|
* @return {Array}
|
|
|
|
|
**/
|
|
|
|
|
_validateHook(hook) {
|
|
|
|
|
if (!Array.isArray(hook)) {
|
|
|
|
|
throw new Error("A hook definition should be an array of functions.");
|
|
|
|
|
}
|
|
|
|
|
return hook.map(fn => {
|
|
|
|
|
if (typeof fn !== "function") {
|
|
|
|
|
throw new Error("A hook definition should be an array of functions.");
|
|
|
|
|
}
|
|
|
|
|
return fn;
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Validates a list of hooks.
|
|
|
|
|
*
|
|
|
|
|
* @param {Object|undefined} hooks
|
|
|
|
|
* @return {Object}
|
|
|
|
|
*/
|
|
|
|
|
_validateHooks(hooks) {
|
|
|
|
|
if (typeof hooks === "undefined") {
|
|
|
|
|
return {};
|
|
|
|
|
}
|
|
|
|
|
if (Array.isArray(hooks)) {
|
|
|
|
|
throw new Error("hooks should be an object, not an array.");
|
|
|
|
|
}
|
|
|
|
|
if (typeof hooks !== "object") {
|
|
|
|
|
throw new Error("hooks should be an object.");
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const validatedHooks = {};
|
|
|
|
|
|
|
|
|
|
for (let hook in hooks) {
|
|
|
|
|
if (AVAILABLE_HOOKS.indexOf(hook) === -1) {
|
|
|
|
|
throw new Error("The hook should be one of " + AVAILABLE_HOOKS.join(", "));
|
|
|
|
|
}
|
|
|
|
|
validatedHooks[hook] = this._validateHook(hooks[hook]);
|
|
|
|
|
}
|
|
|
|
|
return validatedHooks;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Deletes every records in the current collection and marks the collection as
|
|
|
|
|
* never synced.
|
|
|
|
|
*
|
|
|
|
|
* @return {Promise}
|
|
|
|
|
*/
|
|
|
|
|
clear() {
|
2016-10-07 17:27:48 +03:00
|
|
|
|
var _this = this;
|
|
|
|
|
|
2016-11-16 03:38:53 +03:00
|
|
|
|
return _asyncToGenerator(function* () {
|
2016-10-07 17:27:48 +03:00
|
|
|
|
yield _this.db.clear();
|
|
|
|
|
yield _this.db.saveLastModified(null);
|
|
|
|
|
return { data: [], permissions: {} };
|
|
|
|
|
})();
|
2016-04-15 02:07:31 +03:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Encodes a record.
|
|
|
|
|
*
|
|
|
|
|
* @param {String} type Either "remote" or "local".
|
|
|
|
|
* @param {Object} record The record object to encode.
|
|
|
|
|
* @return {Promise}
|
|
|
|
|
*/
|
|
|
|
|
_encodeRecord(type, record) {
|
2017-01-28 03:23:05 +03:00
|
|
|
|
if (!this[`${type}Transformers`].length) {
|
2016-11-16 03:38:53 +03:00
|
|
|
|
return Promise.resolve(record);
|
2016-04-15 02:07:31 +03:00
|
|
|
|
}
|
2017-01-28 03:23:05 +03:00
|
|
|
|
return (0, _utils.waterfall)(this[`${type}Transformers`].map(transformer => {
|
2016-04-15 02:07:31 +03:00
|
|
|
|
return record => transformer.encode(record);
|
|
|
|
|
}), record);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Decodes a record.
|
|
|
|
|
*
|
|
|
|
|
* @param {String} type Either "remote" or "local".
|
|
|
|
|
* @param {Object} record The record object to decode.
|
|
|
|
|
* @return {Promise}
|
|
|
|
|
*/
|
|
|
|
|
_decodeRecord(type, record) {
|
2017-01-28 03:23:05 +03:00
|
|
|
|
if (!this[`${type}Transformers`].length) {
|
2016-11-16 03:38:53 +03:00
|
|
|
|
return Promise.resolve(record);
|
2016-04-15 02:07:31 +03:00
|
|
|
|
}
|
2017-01-28 03:23:05 +03:00
|
|
|
|
return (0, _utils.waterfall)(this[`${type}Transformers`].reverse().map(transformer => {
|
2016-04-15 02:07:31 +03:00
|
|
|
|
return record => transformer.decode(record);
|
|
|
|
|
}), record);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
2016-07-13 22:09:42 +03:00
|
|
|
|
* Adds a record to the local database, asserting that none
|
|
|
|
|
* already exist with this ID.
|
2016-04-15 02:07:31 +03:00
|
|
|
|
*
|
|
|
|
|
* Note: If either the `useRecordId` or `synced` options are true, then the
|
|
|
|
|
* record object must contain the id field to be validated. If none of these
|
|
|
|
|
* options are true, an id is generated using the current IdSchema; in this
|
|
|
|
|
* case, the record passed must not have an id.
|
|
|
|
|
*
|
|
|
|
|
* Options:
|
|
|
|
|
* - {Boolean} synced Sets record status to "synced" (default: `false`).
|
|
|
|
|
* - {Boolean} useRecordId Forces the `id` field from the record to be used,
|
|
|
|
|
* instead of one that is generated automatically
|
|
|
|
|
* (default: `false`).
|
|
|
|
|
*
|
|
|
|
|
* @param {Object} record
|
|
|
|
|
* @param {Object} options
|
|
|
|
|
* @return {Promise}
|
|
|
|
|
*/
|
|
|
|
|
create(record, options = { useRecordId: false, synced: false }) {
|
2016-07-13 22:09:42 +03:00
|
|
|
|
// Validate the record and its ID (if any), even though this
|
|
|
|
|
// validation is also done in the CollectionTransaction method,
|
|
|
|
|
// because we need to pass the ID to preloadIds.
|
2016-11-16 03:38:53 +03:00
|
|
|
|
const reject = msg => Promise.reject(new Error(msg));
|
2016-04-15 02:07:31 +03:00
|
|
|
|
if (typeof record !== "object") {
|
|
|
|
|
return reject("Record is not an object.");
|
|
|
|
|
}
|
2016-07-13 22:09:42 +03:00
|
|
|
|
if ((options.synced || options.useRecordId) && !record.hasOwnProperty("id")) {
|
2016-04-15 02:07:31 +03:00
|
|
|
|
return reject("Missing required Id; synced and useRecordId options require one");
|
|
|
|
|
}
|
2016-07-13 22:09:42 +03:00
|
|
|
|
if (!options.synced && !options.useRecordId && record.hasOwnProperty("id")) {
|
2016-04-15 02:07:31 +03:00
|
|
|
|
return reject("Extraneous Id; can't create a record having one set.");
|
|
|
|
|
}
|
2016-11-16 03:38:53 +03:00
|
|
|
|
const newRecord = _extends({}, record, {
|
2016-04-15 02:07:31 +03:00
|
|
|
|
id: options.synced || options.useRecordId ? record.id : this.idSchema.generate(),
|
|
|
|
|
_status: options.synced ? "synced" : "created"
|
|
|
|
|
});
|
|
|
|
|
if (!this.idSchema.validate(newRecord.id)) {
|
2017-01-28 03:23:05 +03:00
|
|
|
|
return reject(`Invalid Id: ${newRecord.id}`);
|
2016-04-15 02:07:31 +03:00
|
|
|
|
}
|
2016-07-13 22:09:42 +03:00
|
|
|
|
return this.execute(txn => txn.create(newRecord), { preloadIds: [newRecord.id] }).catch(err => {
|
2016-04-15 02:07:31 +03:00
|
|
|
|
if (options.useRecordId) {
|
|
|
|
|
throw new Error("Couldn't create record. It may have been virtually deleted.");
|
|
|
|
|
}
|
|
|
|
|
throw err;
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
2016-07-13 22:09:42 +03:00
|
|
|
|
* Like {@link CollectionTransaction#update}, but wrapped in its own transaction.
|
2016-04-15 02:07:31 +03:00
|
|
|
|
*
|
|
|
|
|
* Options:
|
|
|
|
|
* - {Boolean} synced: Sets record status to "synced" (default: false)
|
|
|
|
|
* - {Boolean} patch: Extends the existing record instead of overwriting it
|
|
|
|
|
* (default: false)
|
|
|
|
|
*
|
|
|
|
|
* @param {Object} record
|
|
|
|
|
* @param {Object} options
|
|
|
|
|
* @return {Promise}
|
|
|
|
|
*/
|
|
|
|
|
update(record, options = { synced: false, patch: false }) {
|
2016-07-13 22:09:42 +03:00
|
|
|
|
// Validate the record and its ID, even though this validation is
|
|
|
|
|
// also done in the CollectionTransaction method, because we need
|
|
|
|
|
// to pass the ID to preloadIds.
|
2016-04-15 02:07:31 +03:00
|
|
|
|
if (typeof record !== "object") {
|
2016-11-16 03:38:53 +03:00
|
|
|
|
return Promise.reject(new Error("Record is not an object."));
|
2016-04-15 02:07:31 +03:00
|
|
|
|
}
|
2016-07-13 22:09:42 +03:00
|
|
|
|
if (!record.hasOwnProperty("id")) {
|
2016-11-16 03:38:53 +03:00
|
|
|
|
return Promise.reject(new Error("Cannot update a record missing id."));
|
2016-04-15 02:07:31 +03:00
|
|
|
|
}
|
|
|
|
|
if (!this.idSchema.validate(record.id)) {
|
2017-01-28 03:23:05 +03:00
|
|
|
|
return Promise.reject(new Error(`Invalid Id: ${record.id}`));
|
2016-04-15 02:07:31 +03:00
|
|
|
|
}
|
2016-07-13 22:09:42 +03:00
|
|
|
|
|
|
|
|
|
return this.execute(txn => txn.update(record, options), { preloadIds: [record.id] });
|
2016-04-15 02:07:31 +03:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
2016-07-13 22:09:42 +03:00
|
|
|
|
* Like {@link CollectionTransaction#upsert}, but wrapped in its own transaction.
|
|
|
|
|
*
|
|
|
|
|
* @param {Object} record
|
|
|
|
|
* @return {Promise}
|
|
|
|
|
*/
|
|
|
|
|
upsert(record) {
|
|
|
|
|
// Validate the record and its ID, even though this validation is
|
|
|
|
|
// also done in the CollectionTransaction method, because we need
|
|
|
|
|
// to pass the ID to preloadIds.
|
|
|
|
|
if (typeof record !== "object") {
|
2016-11-16 03:38:53 +03:00
|
|
|
|
return Promise.reject(new Error("Record is not an object."));
|
2016-07-13 22:09:42 +03:00
|
|
|
|
}
|
|
|
|
|
if (!record.hasOwnProperty("id")) {
|
2016-11-16 03:38:53 +03:00
|
|
|
|
return Promise.reject(new Error("Cannot update a record missing id."));
|
2016-07-13 22:09:42 +03:00
|
|
|
|
}
|
|
|
|
|
if (!this.idSchema.validate(record.id)) {
|
2017-01-28 03:23:05 +03:00
|
|
|
|
return Promise.reject(new Error(`Invalid Id: ${record.id}`));
|
2016-07-13 22:09:42 +03:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return this.execute(txn => txn.upsert(record), { preloadIds: [record.id] });
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Like {@link CollectionTransaction#get}, but wrapped in its own transaction.
|
|
|
|
|
*
|
|
|
|
|
* Options:
|
|
|
|
|
* - {Boolean} includeDeleted: Include virtually deleted records.
|
2016-04-15 02:07:31 +03:00
|
|
|
|
*
|
|
|
|
|
* @param {String} id
|
|
|
|
|
* @param {Object} options
|
|
|
|
|
* @return {Promise}
|
|
|
|
|
*/
|
|
|
|
|
get(id, options = { includeDeleted: false }) {
|
2016-07-13 22:09:42 +03:00
|
|
|
|
return this.execute(txn => txn.get(id, options), { preloadIds: [id] });
|
2016-04-15 02:07:31 +03:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
2016-07-13 22:09:42 +03:00
|
|
|
|
* Like {@link CollectionTransaction#getAny}, but wrapped in its own transaction.
|
|
|
|
|
*
|
|
|
|
|
* @param {String} id
|
|
|
|
|
* @return {Promise}
|
|
|
|
|
*/
|
|
|
|
|
getAny(id) {
|
|
|
|
|
return this.execute(txn => txn.getAny(id), { preloadIds: [id] });
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Same as {@link Collection#delete}, but wrapped in its own transaction.
|
2016-04-15 02:07:31 +03:00
|
|
|
|
*
|
|
|
|
|
* Options:
|
|
|
|
|
* - {Boolean} virtual: When set to `true`, doesn't actually delete the record,
|
|
|
|
|
* update its `_status` attribute to `deleted` instead (default: true)
|
|
|
|
|
*
|
|
|
|
|
* @param {String} id The record's Id.
|
|
|
|
|
* @param {Object} options The options object.
|
|
|
|
|
* @return {Promise}
|
|
|
|
|
*/
|
|
|
|
|
delete(id, options = { virtual: true }) {
|
2016-07-13 22:09:42 +03:00
|
|
|
|
return this.execute(transaction => {
|
|
|
|
|
return transaction.delete(id, options);
|
|
|
|
|
}, { preloadIds: [id] });
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* The same as {@link CollectionTransaction#deleteAny}, but wrapped
|
|
|
|
|
* in its own transaction.
|
|
|
|
|
*
|
|
|
|
|
* @param {String} id The record's Id.
|
|
|
|
|
* @return {Promise}
|
|
|
|
|
*/
|
|
|
|
|
deleteAny(id) {
|
|
|
|
|
return this.execute(txn => txn.deleteAny(id), { preloadIds: [id] });
|
2016-04-15 02:07:31 +03:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Lists records from the local database.
|
|
|
|
|
*
|
|
|
|
|
* Params:
|
|
|
|
|
* - {Object} filters Filter the results (default: `{}`).
|
|
|
|
|
* - {String} order The order to apply (default: `-last_modified`).
|
|
|
|
|
*
|
|
|
|
|
* Options:
|
|
|
|
|
* - {Boolean} includeDeleted: Include virtually deleted records.
|
|
|
|
|
*
|
|
|
|
|
* @param {Object} params The filters and order to apply to the results.
|
|
|
|
|
* @param {Object} options The options object.
|
|
|
|
|
* @return {Promise}
|
|
|
|
|
*/
|
|
|
|
|
list(params = {}, options = { includeDeleted: false }) {
|
2016-10-07 17:27:48 +03:00
|
|
|
|
var _this2 = this;
|
|
|
|
|
|
2016-11-16 03:38:53 +03:00
|
|
|
|
return _asyncToGenerator(function* () {
|
|
|
|
|
params = _extends({ order: "-last_modified", filters: {} }, params);
|
2016-10-07 17:27:48 +03:00
|
|
|
|
const results = yield _this2.db.list(params);
|
2016-04-15 02:07:31 +03:00
|
|
|
|
let data = results;
|
|
|
|
|
if (!options.includeDeleted) {
|
2016-10-07 17:27:48 +03:00
|
|
|
|
data = results.filter(function (record) {
|
|
|
|
|
return record._status !== "deleted";
|
|
|
|
|
});
|
2016-04-15 02:07:31 +03:00
|
|
|
|
}
|
|
|
|
|
return { data, permissions: {} };
|
2016-10-07 17:27:48 +03:00
|
|
|
|
})();
|
2016-04-15 02:07:31 +03:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
2016-10-07 17:27:48 +03:00
|
|
|
|
* Imports remote changes into the local database.
|
|
|
|
|
* This method is in charge of detecting the conflicts, and resolve them
|
|
|
|
|
* according to the specified strategy.
|
2016-04-15 02:07:31 +03:00
|
|
|
|
* @param {SyncResultObject} syncResultObject The sync result object.
|
2016-10-07 17:27:48 +03:00
|
|
|
|
* @param {Array} decodedChanges The list of changes to import in the local database.
|
|
|
|
|
* @param {String} strategy The {@link Collection.strategy} (default: MANUAL)
|
2016-04-15 02:07:31 +03:00
|
|
|
|
* @return {Promise}
|
|
|
|
|
*/
|
2016-10-07 17:27:48 +03:00
|
|
|
|
importChanges(syncResultObject, decodedChanges, strategy = Collection.strategy.MANUAL) {
|
|
|
|
|
var _this3 = this;
|
|
|
|
|
|
2016-11-16 03:38:53 +03:00
|
|
|
|
return _asyncToGenerator(function* () {
|
2016-04-15 02:07:31 +03:00
|
|
|
|
// Retrieve records matching change ids.
|
2016-10-07 17:27:48 +03:00
|
|
|
|
try {
|
|
|
|
|
const { imports, resolved } = yield _this3.db.execute(function (transaction) {
|
|
|
|
|
const imports = decodedChanges.map(function (remote) {
|
|
|
|
|
// Store remote change into local database.
|
|
|
|
|
return importChange(transaction, remote, _this3.localFields);
|
|
|
|
|
});
|
|
|
|
|
const conflicts = imports.filter(function (i) {
|
|
|
|
|
return i.type === "conflicts";
|
|
|
|
|
}).map(function (i) {
|
|
|
|
|
return i.data;
|
|
|
|
|
});
|
|
|
|
|
const resolved = _this3._handleConflicts(transaction, conflicts, strategy);
|
|
|
|
|
return { imports, resolved };
|
|
|
|
|
}, { preload: decodedChanges.map(function (record) {
|
|
|
|
|
return record.id;
|
|
|
|
|
}) });
|
|
|
|
|
|
|
|
|
|
// Lists of created/updated/deleted records
|
|
|
|
|
imports.forEach(function ({ type, data }) {
|
|
|
|
|
return syncResultObject.add(type, data);
|
2016-07-13 22:09:42 +03:00
|
|
|
|
});
|
2016-10-07 17:27:48 +03:00
|
|
|
|
|
|
|
|
|
// Automatically resolved conflicts (if not manual)
|
|
|
|
|
if (resolved.length > 0) {
|
|
|
|
|
syncResultObject.reset("conflicts").add("resolved", resolved);
|
|
|
|
|
}
|
|
|
|
|
} catch (err) {
|
2016-05-02 13:45:50 +03:00
|
|
|
|
const data = {
|
|
|
|
|
type: "incoming",
|
|
|
|
|
message: err.message,
|
|
|
|
|
stack: err.stack
|
|
|
|
|
};
|
2016-04-15 02:07:31 +03:00
|
|
|
|
// XXX one error of the whole transaction instead of per atomic op
|
2016-10-07 17:27:48 +03:00
|
|
|
|
syncResultObject.add("errors", data);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return syncResultObject;
|
|
|
|
|
})();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Imports the responses of pushed changes into the local database.
|
|
|
|
|
* Basically it stores the timestamp assigned by the server into the local
|
|
|
|
|
* database.
|
|
|
|
|
* @param {SyncResultObject} syncResultObject The sync result object.
|
|
|
|
|
* @param {Array} toApplyLocally The list of changes to import in the local database.
|
|
|
|
|
* @param {Array} conflicts The list of conflicts that have to be resolved.
|
|
|
|
|
* @param {String} strategy The {@link Collection.strategy}.
|
|
|
|
|
* @return {Promise}
|
|
|
|
|
*/
|
|
|
|
|
_applyPushedResults(syncResultObject, toApplyLocally, conflicts, strategy = Collection.strategy.MANUAL) {
|
|
|
|
|
var _this4 = this;
|
|
|
|
|
|
2016-11-16 03:38:53 +03:00
|
|
|
|
return _asyncToGenerator(function* () {
|
2016-10-07 17:27:48 +03:00
|
|
|
|
const toDeleteLocally = toApplyLocally.filter(function (r) {
|
|
|
|
|
return r.deleted;
|
|
|
|
|
});
|
|
|
|
|
const toUpdateLocally = toApplyLocally.filter(function (r) {
|
|
|
|
|
return !r.deleted;
|
2016-04-15 02:07:31 +03:00
|
|
|
|
});
|
2016-10-07 17:27:48 +03:00
|
|
|
|
|
|
|
|
|
const { published, resolved } = yield _this4.db.execute(function (transaction) {
|
|
|
|
|
const updated = toUpdateLocally.map(function (record) {
|
|
|
|
|
const synced = markSynced(record);
|
|
|
|
|
transaction.update(synced);
|
|
|
|
|
return synced;
|
|
|
|
|
});
|
|
|
|
|
const deleted = toDeleteLocally.map(function (record) {
|
|
|
|
|
transaction.delete(record.id);
|
|
|
|
|
// Amend result data with the deleted attribute set
|
|
|
|
|
return { id: record.id, deleted: true };
|
|
|
|
|
});
|
|
|
|
|
const published = updated.concat(deleted);
|
|
|
|
|
// Handle conflicts, if any
|
|
|
|
|
const resolved = _this4._handleConflicts(transaction, conflicts, strategy);
|
|
|
|
|
return { published, resolved };
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
syncResultObject.add("published", published);
|
|
|
|
|
|
|
|
|
|
if (resolved.length > 0) {
|
|
|
|
|
syncResultObject.reset("conflicts").reset("resolved").add("resolved", resolved);
|
|
|
|
|
}
|
2016-09-05 20:18:25 +03:00
|
|
|
|
return syncResultObject;
|
2016-10-07 17:27:48 +03:00
|
|
|
|
})();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Handles synchronization conflicts according to specified strategy.
|
|
|
|
|
*
|
|
|
|
|
* @param {SyncResultObject} result The sync result object.
|
|
|
|
|
* @param {String} strategy The {@link Collection.strategy}.
|
|
|
|
|
* @return {Promise}
|
|
|
|
|
*/
|
|
|
|
|
_handleConflicts(transaction, conflicts, strategy) {
|
|
|
|
|
if (strategy === Collection.strategy.MANUAL) {
|
|
|
|
|
return [];
|
|
|
|
|
}
|
|
|
|
|
return conflicts.map(conflict => {
|
|
|
|
|
const resolution = strategy === Collection.strategy.CLIENT_WINS ? conflict.local : conflict.remote;
|
|
|
|
|
const updated = this._resolveRaw(conflict, resolution);
|
|
|
|
|
transaction.update(updated);
|
|
|
|
|
return updated;
|
2016-04-15 02:07:31 +03:00
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
2016-07-13 22:09:42 +03:00
|
|
|
|
/**
|
|
|
|
|
* Execute a bunch of operations in a transaction.
|
|
|
|
|
*
|
|
|
|
|
* This transaction should be atomic -- either all of its operations
|
|
|
|
|
* will succeed, or none will.
|
|
|
|
|
*
|
|
|
|
|
* The argument to this function is itself a function which will be
|
|
|
|
|
* called with a {@link CollectionTransaction}. Collection methods
|
|
|
|
|
* are available on this transaction, but instead of returning
|
|
|
|
|
* promises, they are synchronous. execute() returns a Promise whose
|
|
|
|
|
* value will be the return value of the provided function.
|
|
|
|
|
*
|
|
|
|
|
* Most operations will require access to the record itself, which
|
|
|
|
|
* must be preloaded by passing its ID in the preloadIds option.
|
|
|
|
|
*
|
|
|
|
|
* Options:
|
|
|
|
|
* - {Array} preloadIds: list of IDs to fetch at the beginning of
|
|
|
|
|
* the transaction
|
|
|
|
|
*
|
|
|
|
|
* @return {Promise} Resolves with the result of the given function
|
|
|
|
|
* when the transaction commits.
|
|
|
|
|
*/
|
|
|
|
|
execute(doOperations, { preloadIds = [] } = {}) {
|
|
|
|
|
for (let id of preloadIds) {
|
|
|
|
|
if (!this.idSchema.validate(id)) {
|
2017-01-28 03:23:05 +03:00
|
|
|
|
return Promise.reject(Error(`Invalid Id: ${id}`));
|
2016-07-13 22:09:42 +03:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return this.db.execute(transaction => {
|
|
|
|
|
const txn = new CollectionTransaction(this, transaction);
|
2016-08-25 21:13:15 +03:00
|
|
|
|
const result = doOperations(txn);
|
|
|
|
|
txn.emitEvents();
|
|
|
|
|
return result;
|
2016-07-13 22:09:42 +03:00
|
|
|
|
}, { preload: preloadIds });
|
|
|
|
|
}
|
|
|
|
|
|
2016-04-15 02:07:31 +03:00
|
|
|
|
/**
|
|
|
|
|
* Resets the local records as if they were never synced; existing records are
|
|
|
|
|
* marked as newly created, deleted records are dropped.
|
|
|
|
|
*
|
|
|
|
|
* A next call to {@link Collection.sync} will thus republish the whole
|
|
|
|
|
* content of the local collection to the server.
|
|
|
|
|
*
|
|
|
|
|
* @return {Promise} Resolves with the number of processed records.
|
|
|
|
|
*/
|
|
|
|
|
resetSyncStatus() {
|
2016-10-07 17:27:48 +03:00
|
|
|
|
var _this5 = this;
|
|
|
|
|
|
2016-11-16 03:38:53 +03:00
|
|
|
|
return _asyncToGenerator(function* () {
|
2016-10-07 17:27:48 +03:00
|
|
|
|
const unsynced = yield _this5.list({ filters: { _status: ["deleted", "synced"] }, order: "" }, { includeDeleted: true });
|
|
|
|
|
yield _this5.db.execute(function (transaction) {
|
|
|
|
|
unsynced.data.forEach(function (record) {
|
2016-04-15 02:07:31 +03:00
|
|
|
|
if (record._status === "deleted") {
|
|
|
|
|
// Garbage collect deleted records.
|
|
|
|
|
transaction.delete(record.id);
|
|
|
|
|
} else {
|
|
|
|
|
// Records that were synced become «created».
|
2016-11-16 03:38:53 +03:00
|
|
|
|
transaction.update(_extends({}, record, {
|
2016-04-15 02:07:31 +03:00
|
|
|
|
last_modified: undefined,
|
|
|
|
|
_status: "created"
|
|
|
|
|
}));
|
|
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
});
|
2016-10-07 17:27:48 +03:00
|
|
|
|
_this5._lastModified = null;
|
|
|
|
|
yield _this5.db.saveLastModified(null);
|
|
|
|
|
return unsynced.data.length;
|
|
|
|
|
})();
|
2016-04-15 02:07:31 +03:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Returns an object containing two lists:
|
|
|
|
|
*
|
|
|
|
|
* - `toDelete`: unsynced deleted records we can safely delete;
|
|
|
|
|
* - `toSync`: local updates to send to the server.
|
|
|
|
|
*
|
2016-08-25 21:13:15 +03:00
|
|
|
|
* @return {Promise}
|
2016-04-15 02:07:31 +03:00
|
|
|
|
*/
|
|
|
|
|
gatherLocalChanges() {
|
2016-10-07 17:27:48 +03:00
|
|
|
|
var _this6 = this;
|
|
|
|
|
|
2016-11-16 03:38:53 +03:00
|
|
|
|
return _asyncToGenerator(function* () {
|
2016-10-07 17:27:48 +03:00
|
|
|
|
const unsynced = yield _this6.list({ filters: { _status: ["created", "updated"] }, order: "" });
|
|
|
|
|
const deleted = yield _this6.list({ filters: { _status: "deleted" }, order: "" }, { includeDeleted: true });
|
|
|
|
|
|
2017-01-28 03:23:05 +03:00
|
|
|
|
return yield Promise.all(unsynced.data.concat(deleted.data).map(_this6._encodeRecord.bind(_this6, "remote")));
|
2016-10-07 17:27:48 +03:00
|
|
|
|
})();
|
2016-04-15 02:07:31 +03:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Fetch remote changes, import them to the local database, and handle
|
|
|
|
|
* conflicts according to `options.strategy`. Then, updates the passed
|
|
|
|
|
* {@link SyncResultObject} with import results.
|
|
|
|
|
*
|
|
|
|
|
* Options:
|
|
|
|
|
* - {String} strategy: The selected sync strategy.
|
|
|
|
|
*
|
2016-07-13 22:09:42 +03:00
|
|
|
|
* @param {KintoClient.Collection} client Kinto client Collection instance.
|
|
|
|
|
* @param {SyncResultObject} syncResultObject The sync result object.
|
|
|
|
|
* @param {Object} options
|
2016-04-15 02:07:31 +03:00
|
|
|
|
* @return {Promise}
|
|
|
|
|
*/
|
2016-07-13 22:09:42 +03:00
|
|
|
|
pullChanges(client, syncResultObject, options = {}) {
|
2016-10-07 17:27:48 +03:00
|
|
|
|
var _this7 = this;
|
|
|
|
|
|
2016-11-16 03:38:53 +03:00
|
|
|
|
return _asyncToGenerator(function* () {
|
2016-10-07 17:27:48 +03:00
|
|
|
|
if (!syncResultObject.ok) {
|
|
|
|
|
return syncResultObject;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const since = _this7.lastModified ? _this7.lastModified : yield _this7.db.getLastModified();
|
|
|
|
|
|
2016-11-16 03:38:53 +03:00
|
|
|
|
options = _extends({
|
2016-10-07 17:27:48 +03:00
|
|
|
|
strategy: Collection.strategy.MANUAL,
|
|
|
|
|
lastModified: since,
|
|
|
|
|
headers: {}
|
|
|
|
|
}, options);
|
|
|
|
|
|
|
|
|
|
// Optionally ignore some records when pulling for changes.
|
|
|
|
|
// (avoid redownloading our own changes on last step of #sync())
|
|
|
|
|
let filters;
|
|
|
|
|
if (options.exclude) {
|
|
|
|
|
// Limit the list of excluded records to the first 50 records in order
|
|
|
|
|
// to remain under de-facto URL size limit (~2000 chars).
|
|
|
|
|
// http://stackoverflow.com/questions/417142/what-is-the-maximum-length-of-a-url-in-different-browsers/417184#417184
|
|
|
|
|
const exclude_id = options.exclude.slice(0, 50).map(function (r) {
|
|
|
|
|
return r.id;
|
|
|
|
|
}).join(",");
|
|
|
|
|
filters = { exclude_id };
|
|
|
|
|
}
|
|
|
|
|
// First fetch remote changes from the server
|
|
|
|
|
const { data, last_modified } = yield client.listRecords({
|
|
|
|
|
// Since should be ETag (see https://github.com/Kinto/kinto.js/issues/356)
|
2017-01-28 03:23:05 +03:00
|
|
|
|
since: options.lastModified ? `${options.lastModified}` : undefined,
|
2016-10-07 17:27:48 +03:00
|
|
|
|
headers: options.headers,
|
2017-01-18 16:53:52 +03:00
|
|
|
|
retry: options.retry,
|
2016-10-07 17:27:48 +03:00
|
|
|
|
filters
|
|
|
|
|
});
|
2016-04-15 02:07:31 +03:00
|
|
|
|
// last_modified is the ETag header value (string).
|
|
|
|
|
// For retro-compatibility with first kinto.js versions
|
|
|
|
|
// parse it to integer.
|
2016-07-13 22:09:42 +03:00
|
|
|
|
const unquoted = last_modified ? parseInt(last_modified, 10) : undefined;
|
2016-04-15 02:07:31 +03:00
|
|
|
|
|
|
|
|
|
// Check if server was flushed.
|
|
|
|
|
// This is relevant for the Kinto demo server
|
|
|
|
|
// (and thus for many new comers).
|
|
|
|
|
const localSynced = options.lastModified;
|
|
|
|
|
const serverChanged = unquoted > options.lastModified;
|
|
|
|
|
const emptyCollection = data.length === 0;
|
2016-07-13 22:09:42 +03:00
|
|
|
|
if (!options.exclude && localSynced && serverChanged && emptyCollection) {
|
2016-04-15 02:07:31 +03:00
|
|
|
|
throw Error("Server has been flushed.");
|
|
|
|
|
}
|
|
|
|
|
|
2016-10-07 17:27:48 +03:00
|
|
|
|
syncResultObject.lastModified = unquoted;
|
|
|
|
|
|
|
|
|
|
// Decode incoming changes.
|
2016-11-16 03:38:53 +03:00
|
|
|
|
const decodedChanges = yield Promise.all(data.map(function (change) {
|
2016-10-07 17:27:48 +03:00
|
|
|
|
return _this7._decodeRecord("remote", change);
|
|
|
|
|
}));
|
|
|
|
|
// Hook receives decoded records.
|
|
|
|
|
const payload = { lastModified: unquoted, changes: decodedChanges };
|
|
|
|
|
const afterHooks = yield _this7.applyHook("incoming-changes", payload);
|
|
|
|
|
|
|
|
|
|
// No change, nothing to import.
|
|
|
|
|
if (afterHooks.changes.length > 0) {
|
|
|
|
|
// Reflect these changes locally
|
|
|
|
|
yield _this7.importChanges(syncResultObject, afterHooks.changes, options.strategy);
|
|
|
|
|
}
|
|
|
|
|
return syncResultObject;
|
|
|
|
|
})();
|
2016-04-15 02:07:31 +03:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
applyHook(hookName, payload) {
|
|
|
|
|
if (typeof this.hooks[hookName] == "undefined") {
|
2016-11-16 03:38:53 +03:00
|
|
|
|
return Promise.resolve(payload);
|
2016-04-15 02:07:31 +03:00
|
|
|
|
}
|
|
|
|
|
return (0, _utils.waterfall)(this.hooks[hookName].map(hook => {
|
2016-07-13 22:09:42 +03:00
|
|
|
|
return record => {
|
|
|
|
|
const result = hook(payload, this);
|
|
|
|
|
const resultThenable = result && typeof result.then === "function";
|
|
|
|
|
const resultChanges = result && result.hasOwnProperty("changes");
|
|
|
|
|
if (!(resultThenable || resultChanges)) {
|
2017-01-28 03:23:05 +03:00
|
|
|
|
throw new Error(`Invalid return value for hook: ${JSON.stringify(result)} has no 'then()' or 'changes' properties`);
|
2016-07-13 22:09:42 +03:00
|
|
|
|
}
|
|
|
|
|
return result;
|
|
|
|
|
};
|
2016-04-15 02:07:31 +03:00
|
|
|
|
}), payload);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Publish local changes to the remote server and updates the passed
|
|
|
|
|
* {@link SyncResultObject} with publication results.
|
|
|
|
|
*
|
2016-07-13 22:09:42 +03:00
|
|
|
|
* @param {KintoClient.Collection} client Kinto client Collection instance.
|
|
|
|
|
* @param {SyncResultObject} syncResultObject The sync result object.
|
2016-10-07 17:27:48 +03:00
|
|
|
|
* @param {Object} changes The change object.
|
|
|
|
|
* @param {Array} changes.toDelete The list of records to delete.
|
|
|
|
|
* @param {Array} changes.toSync The list of records to create/update.
|
2016-07-13 22:09:42 +03:00
|
|
|
|
* @param {Object} options The options object.
|
2016-04-15 02:07:31 +03:00
|
|
|
|
* @return {Promise}
|
|
|
|
|
*/
|
2017-01-28 03:23:05 +03:00
|
|
|
|
pushChanges(client, changes, syncResultObject, options = {}) {
|
2016-10-07 17:27:48 +03:00
|
|
|
|
var _this8 = this;
|
2016-04-15 02:07:31 +03:00
|
|
|
|
|
2016-11-16 03:38:53 +03:00
|
|
|
|
return _asyncToGenerator(function* () {
|
2016-10-07 17:27:48 +03:00
|
|
|
|
if (!syncResultObject.ok) {
|
|
|
|
|
return syncResultObject;
|
|
|
|
|
}
|
|
|
|
|
const safe = !options.strategy || options.strategy !== Collection.CLIENT_WINS;
|
2017-01-28 03:23:05 +03:00
|
|
|
|
const toDelete = changes.filter(function (r) {
|
|
|
|
|
return r._status == "deleted";
|
|
|
|
|
});
|
|
|
|
|
const toSync = changes.filter(function (r) {
|
|
|
|
|
return r._status != "deleted";
|
|
|
|
|
});
|
2016-10-07 17:27:48 +03:00
|
|
|
|
|
|
|
|
|
// Perform a batch request with every changes.
|
|
|
|
|
const synced = yield client.batch(function (batch) {
|
|
|
|
|
toDelete.forEach(function (r) {
|
2016-04-15 02:07:31 +03:00
|
|
|
|
// never published locally deleted records should not be pusblished
|
|
|
|
|
if (r.last_modified) {
|
|
|
|
|
batch.deleteRecord(r);
|
|
|
|
|
}
|
|
|
|
|
});
|
2016-10-07 17:27:48 +03:00
|
|
|
|
toSync.forEach(function (r) {
|
2016-07-13 22:09:42 +03:00
|
|
|
|
// Clean local fields (like _status) before sending to server.
|
2016-10-07 17:27:48 +03:00
|
|
|
|
const published = _this8.cleanLocalFields(r);
|
2016-07-13 22:09:42 +03:00
|
|
|
|
if (r._status === "created") {
|
|
|
|
|
batch.createRecord(published);
|
2016-04-15 02:07:31 +03:00
|
|
|
|
} else {
|
2016-07-13 22:09:42 +03:00
|
|
|
|
batch.updateRecord(published);
|
2016-04-15 02:07:31 +03:00
|
|
|
|
}
|
|
|
|
|
});
|
2017-01-18 16:53:52 +03:00
|
|
|
|
}, {
|
|
|
|
|
headers: options.headers,
|
|
|
|
|
retry: options.retry,
|
|
|
|
|
safe,
|
|
|
|
|
aggregate: true
|
|
|
|
|
});
|
2016-10-07 17:27:48 +03:00
|
|
|
|
|
|
|
|
|
// Store outgoing errors into sync result object
|
|
|
|
|
syncResultObject.add("errors", synced.errors.map(function (e) {
|
2016-11-16 03:38:53 +03:00
|
|
|
|
return _extends({}, e, { type: "outgoing" });
|
2016-04-15 02:07:31 +03:00
|
|
|
|
}));
|
|
|
|
|
|
2016-10-07 17:27:48 +03:00
|
|
|
|
// Store outgoing conflicts into sync result object
|
|
|
|
|
const conflicts = [];
|
2017-01-18 16:53:52 +03:00
|
|
|
|
for (let _ref of synced.conflicts) {
|
|
|
|
|
let { type, local, remote } = _ref;
|
|
|
|
|
|
2016-08-25 21:13:15 +03:00
|
|
|
|
// Note: we ensure that local data are actually available, as they may
|
|
|
|
|
// be missing in the case of a published deletion.
|
2016-10-07 17:27:48 +03:00
|
|
|
|
const safeLocal = local && local.data || { id: remote.id };
|
|
|
|
|
const realLocal = yield _this8._decodeRecord("remote", safeLocal);
|
|
|
|
|
const realRemote = yield _this8._decodeRecord("remote", remote);
|
|
|
|
|
const conflict = { type, local: realLocal, remote: realRemote };
|
|
|
|
|
conflicts.push(conflict);
|
|
|
|
|
}
|
2016-07-13 22:09:42 +03:00
|
|
|
|
syncResultObject.add("conflicts", conflicts);
|
|
|
|
|
|
|
|
|
|
// Records that must be deleted are either deletions that were pushed
|
|
|
|
|
// to server (published) or deleted records that were never pushed (skipped).
|
2016-10-07 17:27:48 +03:00
|
|
|
|
const missingRemotely = synced.skipped.map(function (r) {
|
2016-11-16 03:38:53 +03:00
|
|
|
|
return _extends({}, r, { deleted: true });
|
2016-07-13 22:09:42 +03:00
|
|
|
|
});
|
|
|
|
|
|
2016-10-07 17:27:48 +03:00
|
|
|
|
// For created and updated records, the last_modified coming from server
|
|
|
|
|
// will be stored locally.
|
|
|
|
|
// Reflect publication results locally using the response from
|
|
|
|
|
// the batch request.
|
|
|
|
|
const published = synced.published.map(function (c) {
|
|
|
|
|
return c.data;
|
2016-04-15 02:07:31 +03:00
|
|
|
|
});
|
2016-10-07 17:27:48 +03:00
|
|
|
|
const toApplyLocally = published.concat(missingRemotely);
|
|
|
|
|
|
|
|
|
|
// Apply the decode transformers, if any
|
2016-11-16 03:38:53 +03:00
|
|
|
|
const decoded = yield Promise.all(toApplyLocally.map(function (record) {
|
2016-10-07 17:27:48 +03:00
|
|
|
|
return _this8._decodeRecord("remote", record);
|
|
|
|
|
}));
|
|
|
|
|
|
|
|
|
|
// We have to update the local records with the responses of the server
|
|
|
|
|
// (eg. last_modified values etc.).
|
|
|
|
|
if (decoded.length > 0 || conflicts.length > 0) {
|
|
|
|
|
yield _this8._applyPushedResults(syncResultObject, decoded, conflicts, options.strategy);
|
2016-04-15 02:07:31 +03:00
|
|
|
|
}
|
2016-10-07 17:27:48 +03:00
|
|
|
|
|
|
|
|
|
return syncResultObject;
|
|
|
|
|
})();
|
2016-04-15 02:07:31 +03:00
|
|
|
|
}
|
|
|
|
|
|
2016-07-13 22:09:42 +03:00
|
|
|
|
/**
|
|
|
|
|
* Return a copy of the specified record without the local fields.
|
|
|
|
|
*
|
|
|
|
|
* @param {Object} record A record with potential local fields.
|
|
|
|
|
* @return {Object}
|
|
|
|
|
*/
|
|
|
|
|
cleanLocalFields(record) {
|
|
|
|
|
const localKeys = RECORD_FIELDS_TO_CLEAN.concat(this.localFields);
|
|
|
|
|
return (0, _utils.omitKeys)(record, localKeys);
|
|
|
|
|
}
|
|
|
|
|
|
2016-04-15 02:07:31 +03:00
|
|
|
|
/**
|
|
|
|
|
* Resolves a conflict, updating local record according to proposed
|
|
|
|
|
* resolution — keeping remote record `last_modified` value as a reference for
|
|
|
|
|
* further batch sending.
|
|
|
|
|
*
|
|
|
|
|
* @param {Object} conflict The conflict object.
|
|
|
|
|
* @param {Object} resolution The proposed record.
|
|
|
|
|
* @return {Promise}
|
|
|
|
|
*/
|
|
|
|
|
resolve(conflict, resolution) {
|
2016-07-13 22:09:42 +03:00
|
|
|
|
return this.db.execute(transaction => {
|
|
|
|
|
const updated = this._resolveRaw(conflict, resolution);
|
|
|
|
|
transaction.update(updated);
|
|
|
|
|
return { data: updated, permissions: {} };
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* @private
|
|
|
|
|
*/
|
|
|
|
|
_resolveRaw(conflict, resolution) {
|
2016-11-16 03:38:53 +03:00
|
|
|
|
const resolved = _extends({}, resolution, {
|
2016-04-15 02:07:31 +03:00
|
|
|
|
// Ensure local record has the latest authoritative timestamp
|
|
|
|
|
last_modified: conflict.remote.last_modified
|
2016-07-13 22:09:42 +03:00
|
|
|
|
});
|
|
|
|
|
// If the resolution object is strictly equal to the
|
|
|
|
|
// remote record, then we can mark it as synced locally.
|
|
|
|
|
// Otherwise, mark it as updated (so that the resolution is pushed).
|
|
|
|
|
const synced = (0, _utils.deepEqual)(resolved, conflict.remote);
|
|
|
|
|
return markStatus(resolved, synced ? "synced" : "updated");
|
2016-04-15 02:07:31 +03:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Synchronize remote and local data. The promise will resolve with a
|
|
|
|
|
* {@link SyncResultObject}, though will reject:
|
|
|
|
|
*
|
|
|
|
|
* - if the server is currently backed off;
|
|
|
|
|
* - if the server has been detected flushed.
|
|
|
|
|
*
|
|
|
|
|
* Options:
|
|
|
|
|
* - {Object} headers: HTTP headers to attach to outgoing requests.
|
2017-01-18 16:53:52 +03:00
|
|
|
|
* - {Number} retry: Number of retries when server fails to process the request (default: 1).
|
2016-04-15 02:07:31 +03:00
|
|
|
|
* - {Collection.strategy} strategy: See {@link Collection.strategy}.
|
|
|
|
|
* - {Boolean} ignoreBackoff: Force synchronization even if server is currently
|
|
|
|
|
* backed off.
|
2016-07-13 22:09:42 +03:00
|
|
|
|
* - {String} bucket: The remove bucket id to use (default: null)
|
|
|
|
|
* - {String} collection: The remove collection id to use (default: null)
|
2016-04-15 02:07:31 +03:00
|
|
|
|
* - {String} remote The remote Kinto server endpoint to use (default: null).
|
|
|
|
|
*
|
|
|
|
|
* @param {Object} options Options.
|
|
|
|
|
* @return {Promise}
|
|
|
|
|
* @throws {Error} If an invalid remote option is passed.
|
|
|
|
|
*/
|
|
|
|
|
sync(options = {
|
|
|
|
|
strategy: Collection.strategy.MANUAL,
|
|
|
|
|
headers: {},
|
2017-01-18 16:53:52 +03:00
|
|
|
|
retry: 1,
|
2016-04-15 02:07:31 +03:00
|
|
|
|
ignoreBackoff: false,
|
2016-07-13 22:09:42 +03:00
|
|
|
|
bucket: null,
|
|
|
|
|
collection: null,
|
2016-04-15 02:07:31 +03:00
|
|
|
|
remote: null
|
|
|
|
|
}) {
|
2016-10-07 17:27:48 +03:00
|
|
|
|
var _this9 = this;
|
2016-07-13 22:09:42 +03:00
|
|
|
|
|
2016-11-16 03:38:53 +03:00
|
|
|
|
return _asyncToGenerator(function* () {
|
2017-01-18 16:53:52 +03:00
|
|
|
|
options = _extends({}, options, {
|
|
|
|
|
bucket: options.bucket || _this9.bucket,
|
|
|
|
|
collection: options.collection || _this9.name
|
|
|
|
|
});
|
|
|
|
|
|
2016-10-07 17:27:48 +03:00
|
|
|
|
const previousRemote = _this9.api.remote;
|
|
|
|
|
if (options.remote) {
|
|
|
|
|
// Note: setting the remote ensures it's valid, throws when invalid.
|
|
|
|
|
_this9.api.remote = options.remote;
|
2016-04-15 02:07:31 +03:00
|
|
|
|
}
|
2016-10-07 17:27:48 +03:00
|
|
|
|
if (!options.ignoreBackoff && _this9.api.backoff > 0) {
|
|
|
|
|
const seconds = Math.ceil(_this9.api.backoff / 1000);
|
2017-01-28 03:23:05 +03:00
|
|
|
|
return Promise.reject(new Error(`Server is asking clients to back off; retry in ${seconds}s or use the ignoreBackoff option.`));
|
2016-09-05 20:18:25 +03:00
|
|
|
|
}
|
|
|
|
|
|
2017-01-18 16:53:52 +03:00
|
|
|
|
const client = _this9.api.bucket(options.bucket).collection(options.collection);
|
2016-10-07 17:27:48 +03:00
|
|
|
|
|
|
|
|
|
const result = new SyncResultObject();
|
|
|
|
|
try {
|
|
|
|
|
// Fetch last changes from the server.
|
|
|
|
|
yield _this9.pullChanges(client, result, options);
|
|
|
|
|
const { lastModified } = result;
|
|
|
|
|
|
|
|
|
|
// Fetch local changes
|
2017-01-28 03:23:05 +03:00
|
|
|
|
const toSync = yield _this9.gatherLocalChanges();
|
2016-10-07 17:27:48 +03:00
|
|
|
|
|
|
|
|
|
// Publish local changes and pull local resolutions
|
2017-01-28 03:23:05 +03:00
|
|
|
|
yield _this9.pushChanges(client, toSync, result, options);
|
2016-10-07 17:27:48 +03:00
|
|
|
|
|
|
|
|
|
// Publish local resolution of push conflicts to server (on CLIENT_WINS)
|
|
|
|
|
const resolvedUnsynced = result.resolved.filter(function (r) {
|
|
|
|
|
return r._status !== "synced";
|
|
|
|
|
});
|
|
|
|
|
if (resolvedUnsynced.length > 0) {
|
2016-11-16 03:38:53 +03:00
|
|
|
|
const resolvedEncoded = yield Promise.all(resolvedUnsynced.map(_this9._encodeRecord.bind(_this9, "remote")));
|
2017-01-28 03:23:05 +03:00
|
|
|
|
yield _this9.pushChanges(client, resolvedEncoded, result, options);
|
2016-10-07 17:27:48 +03:00
|
|
|
|
}
|
|
|
|
|
// Perform a last pull to catch changes that occured after the last pull,
|
|
|
|
|
// while local changes were pushed. Do not do it nothing was pushed.
|
|
|
|
|
if (result.published.length > 0) {
|
|
|
|
|
// Avoid redownloading our own changes during the last pull.
|
2016-11-16 03:38:53 +03:00
|
|
|
|
const pullOpts = _extends({}, options, { lastModified, exclude: result.published });
|
2016-10-07 17:27:48 +03:00
|
|
|
|
yield _this9.pullChanges(client, result, pullOpts);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Don't persist lastModified value if any conflict or error occured
|
|
|
|
|
if (result.ok) {
|
|
|
|
|
// No conflict occured, persist collection's lastModified value
|
|
|
|
|
_this9._lastModified = yield _this9.db.saveLastModified(result.lastModified);
|
|
|
|
|
}
|
2017-01-18 16:53:52 +03:00
|
|
|
|
} catch (e) {
|
|
|
|
|
_this9.events.emit("sync:error", _extends({}, options, { error: e }));
|
|
|
|
|
throw e;
|
2016-10-07 17:27:48 +03:00
|
|
|
|
} finally {
|
|
|
|
|
// Ensure API default remote is reverted if a custom one's been used
|
|
|
|
|
_this9.api.remote = previousRemote;
|
|
|
|
|
}
|
2017-01-18 16:53:52 +03:00
|
|
|
|
_this9.events.emit("sync:success", _extends({}, options, { result }));
|
2016-10-07 17:27:48 +03:00
|
|
|
|
return result;
|
|
|
|
|
})();
|
2016-04-15 02:07:31 +03:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Load a list of records already synced with the remote server.
|
|
|
|
|
*
|
|
|
|
|
* The local records which are unsynced or whose timestamp is either missing
|
|
|
|
|
* or superior to those being loaded will be ignored.
|
|
|
|
|
*
|
|
|
|
|
* @param {Array} records The previously exported list of records to load.
|
|
|
|
|
* @return {Promise} with the effectively imported records.
|
|
|
|
|
*/
|
|
|
|
|
loadDump(records) {
|
2016-10-07 17:27:48 +03:00
|
|
|
|
var _this10 = this;
|
2016-04-15 02:07:31 +03:00
|
|
|
|
|
2016-11-16 03:38:53 +03:00
|
|
|
|
return _asyncToGenerator(function* () {
|
2016-10-07 17:27:48 +03:00
|
|
|
|
if (!Array.isArray(records)) {
|
|
|
|
|
throw new Error("Records is not an array.");
|
2016-04-15 02:07:31 +03:00
|
|
|
|
}
|
|
|
|
|
|
2016-10-07 17:27:48 +03:00
|
|
|
|
for (let record of records) {
|
|
|
|
|
if (!record.hasOwnProperty("id") || !_this10.idSchema.validate(record.id)) {
|
2016-11-16 03:38:53 +03:00
|
|
|
|
throw new Error("Record has invalid ID: " + JSON.stringify(record));
|
2016-10-07 17:27:48 +03:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (!record.last_modified) {
|
2016-11-16 03:38:53 +03:00
|
|
|
|
throw new Error("Record has no last_modified value: " + JSON.stringify(record));
|
2016-10-07 17:27:48 +03:00
|
|
|
|
}
|
2016-04-15 02:07:31 +03:00
|
|
|
|
}
|
|
|
|
|
|
2016-10-07 17:27:48 +03:00
|
|
|
|
// Fetch all existing records from local database,
|
|
|
|
|
// and skip those who are newer or not marked as synced.
|
2016-04-15 02:07:31 +03:00
|
|
|
|
|
2016-10-07 17:27:48 +03:00
|
|
|
|
// XXX filter by status / ids in records
|
2016-04-15 02:07:31 +03:00
|
|
|
|
|
2016-10-07 17:27:48 +03:00
|
|
|
|
const { data } = yield _this10.list({}, { includeDeleted: true });
|
|
|
|
|
const existingById = data.reduce(function (acc, record) {
|
2016-04-15 02:07:31 +03:00
|
|
|
|
acc[record.id] = record;
|
|
|
|
|
return acc;
|
|
|
|
|
}, {});
|
2016-10-07 17:27:48 +03:00
|
|
|
|
|
|
|
|
|
const newRecords = records.filter(function (record) {
|
2016-04-15 02:07:31 +03:00
|
|
|
|
const localRecord = existingById[record.id];
|
|
|
|
|
const shouldKeep =
|
|
|
|
|
// No local record with this id.
|
|
|
|
|
localRecord === undefined ||
|
|
|
|
|
// Or local record is synced
|
|
|
|
|
localRecord._status === "synced" &&
|
|
|
|
|
// And was synced from server
|
|
|
|
|
localRecord.last_modified !== undefined &&
|
|
|
|
|
// And is older than imported one.
|
|
|
|
|
record.last_modified > localRecord.last_modified;
|
|
|
|
|
return shouldKeep;
|
|
|
|
|
});
|
2016-10-07 17:27:48 +03:00
|
|
|
|
|
|
|
|
|
return yield _this10.db.loadDump(newRecords.map(markSynced));
|
|
|
|
|
})();
|
2016-04-15 02:07:31 +03:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2016-07-13 22:09:42 +03:00
|
|
|
|
exports.default = Collection; /**
|
|
|
|
|
* A Collection-oriented wrapper for an adapter's transaction.
|
|
|
|
|
*
|
|
|
|
|
* This defines the high-level functions available on a collection.
|
|
|
|
|
* The collection itself offers functions of the same name. These will
|
|
|
|
|
* perform just one operation in its own transaction.
|
|
|
|
|
*/
|
|
|
|
|
|
|
|
|
|
class CollectionTransaction {
|
|
|
|
|
constructor(collection, adapterTransaction) {
|
|
|
|
|
this.collection = collection;
|
|
|
|
|
this.adapterTransaction = adapterTransaction;
|
2016-08-25 21:13:15 +03:00
|
|
|
|
|
|
|
|
|
this._events = [];
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
_queueEvent(action, payload) {
|
|
|
|
|
this._events.push({ action, payload });
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Emit queued events, to be called once every transaction operations have
|
|
|
|
|
* been executed successfully.
|
|
|
|
|
*/
|
|
|
|
|
emitEvents() {
|
2017-01-18 16:53:52 +03:00
|
|
|
|
for (let _ref2 of this._events) {
|
|
|
|
|
let { action, payload } = _ref2;
|
|
|
|
|
|
2016-08-25 21:13:15 +03:00
|
|
|
|
this.collection.events.emit(action, payload);
|
|
|
|
|
}
|
|
|
|
|
if (this._events.length > 0) {
|
2016-11-16 03:38:53 +03:00
|
|
|
|
const targets = this._events.map(({ action, payload }) => _extends({ action }, payload));
|
2016-08-25 21:13:15 +03:00
|
|
|
|
this.collection.events.emit("change", { targets });
|
|
|
|
|
}
|
|
|
|
|
this._events = [];
|
2016-07-13 22:09:42 +03:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Retrieve a record by its id from the local database, or
|
|
|
|
|
* undefined if none exists.
|
|
|
|
|
*
|
|
|
|
|
* This will also return virtually deleted records.
|
|
|
|
|
*
|
|
|
|
|
* @param {String} id
|
|
|
|
|
* @return {Object}
|
|
|
|
|
*/
|
|
|
|
|
getAny(id) {
|
|
|
|
|
const record = this.adapterTransaction.get(id);
|
|
|
|
|
return { data: record, permissions: {} };
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Retrieve a record by its id from the local database.
|
|
|
|
|
*
|
|
|
|
|
* Options:
|
|
|
|
|
* - {Boolean} includeDeleted: Include virtually deleted records.
|
|
|
|
|
*
|
|
|
|
|
* @param {String} id
|
|
|
|
|
* @param {Object} options
|
|
|
|
|
* @return {Object}
|
|
|
|
|
*/
|
|
|
|
|
get(id, options = { includeDeleted: false }) {
|
|
|
|
|
const res = this.getAny(id);
|
|
|
|
|
if (!res.data || !options.includeDeleted && res.data._status === "deleted") {
|
2017-01-28 03:23:05 +03:00
|
|
|
|
throw new Error(`Record with id=${id} not found.`);
|
2016-07-13 22:09:42 +03:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return res;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Deletes a record from the local database.
|
|
|
|
|
*
|
|
|
|
|
* Options:
|
|
|
|
|
* - {Boolean} virtual: When set to `true`, doesn't actually delete the record,
|
|
|
|
|
* update its `_status` attribute to `deleted` instead (default: true)
|
|
|
|
|
*
|
|
|
|
|
* @param {String} id The record's Id.
|
|
|
|
|
* @param {Object} options The options object.
|
|
|
|
|
* @return {Object}
|
|
|
|
|
*/
|
|
|
|
|
delete(id, options = { virtual: true }) {
|
|
|
|
|
// Ensure the record actually exists.
|
|
|
|
|
const existing = this.adapterTransaction.get(id);
|
|
|
|
|
const alreadyDeleted = existing && existing._status == "deleted";
|
|
|
|
|
if (!existing || alreadyDeleted && options.virtual) {
|
2017-01-28 03:23:05 +03:00
|
|
|
|
throw new Error(`Record with id=${id} not found.`);
|
2016-07-13 22:09:42 +03:00
|
|
|
|
}
|
|
|
|
|
// Virtual updates status.
|
|
|
|
|
if (options.virtual) {
|
|
|
|
|
this.adapterTransaction.update(markDeleted(existing));
|
|
|
|
|
} else {
|
|
|
|
|
// Delete for real.
|
|
|
|
|
this.adapterTransaction.delete(id);
|
|
|
|
|
}
|
2016-08-25 21:13:15 +03:00
|
|
|
|
this._queueEvent("delete", { data: existing });
|
2016-07-13 22:09:42 +03:00
|
|
|
|
return { data: existing, permissions: {} };
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Deletes a record from the local database, if any exists.
|
|
|
|
|
* Otherwise, do nothing.
|
|
|
|
|
*
|
|
|
|
|
* @param {String} id The record's Id.
|
|
|
|
|
* @return {Object}
|
|
|
|
|
*/
|
|
|
|
|
deleteAny(id) {
|
|
|
|
|
const existing = this.adapterTransaction.get(id);
|
|
|
|
|
if (existing) {
|
|
|
|
|
this.adapterTransaction.update(markDeleted(existing));
|
2016-08-25 21:13:15 +03:00
|
|
|
|
this._queueEvent("delete", { data: existing });
|
2016-07-13 22:09:42 +03:00
|
|
|
|
}
|
2016-11-16 03:38:53 +03:00
|
|
|
|
return { data: _extends({ id }, existing), deleted: !!existing, permissions: {} };
|
2016-07-13 22:09:42 +03:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Adds a record to the local database, asserting that none
|
|
|
|
|
* already exist with this ID.
|
|
|
|
|
*
|
|
|
|
|
* @param {Object} record, which must contain an ID
|
|
|
|
|
* @return {Object}
|
|
|
|
|
*/
|
|
|
|
|
create(record) {
|
|
|
|
|
if (typeof record !== "object") {
|
|
|
|
|
throw new Error("Record is not an object.");
|
|
|
|
|
}
|
|
|
|
|
if (!record.hasOwnProperty("id")) {
|
|
|
|
|
throw new Error("Cannot create a record missing id");
|
|
|
|
|
}
|
|
|
|
|
if (!this.collection.idSchema.validate(record.id)) {
|
2017-01-28 03:23:05 +03:00
|
|
|
|
throw new Error(`Invalid Id: ${record.id}`);
|
2016-07-13 22:09:42 +03:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
this.adapterTransaction.create(record);
|
2016-08-25 21:13:15 +03:00
|
|
|
|
this._queueEvent("create", { data: record });
|
2016-07-13 22:09:42 +03:00
|
|
|
|
return { data: record, permissions: {} };
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Updates a record from the local database.
|
|
|
|
|
*
|
|
|
|
|
* Options:
|
|
|
|
|
* - {Boolean} synced: Sets record status to "synced" (default: false)
|
|
|
|
|
* - {Boolean} patch: Extends the existing record instead of overwriting it
|
|
|
|
|
* (default: false)
|
|
|
|
|
*
|
|
|
|
|
* @param {Object} record
|
|
|
|
|
* @param {Object} options
|
|
|
|
|
* @return {Object}
|
|
|
|
|
*/
|
|
|
|
|
update(record, options = { synced: false, patch: false }) {
|
|
|
|
|
if (typeof record !== "object") {
|
|
|
|
|
throw new Error("Record is not an object.");
|
|
|
|
|
}
|
|
|
|
|
if (!record.hasOwnProperty("id")) {
|
|
|
|
|
throw new Error("Cannot update a record missing id.");
|
|
|
|
|
}
|
|
|
|
|
if (!this.collection.idSchema.validate(record.id)) {
|
2017-01-28 03:23:05 +03:00
|
|
|
|
throw new Error(`Invalid Id: ${record.id}`);
|
2016-07-13 22:09:42 +03:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const oldRecord = this.adapterTransaction.get(record.id);
|
|
|
|
|
if (!oldRecord) {
|
2017-01-28 03:23:05 +03:00
|
|
|
|
throw new Error(`Record with id=${record.id} not found.`);
|
2016-07-13 22:09:42 +03:00
|
|
|
|
}
|
2016-11-16 03:38:53 +03:00
|
|
|
|
const newRecord = options.patch ? _extends({}, oldRecord, record) : record;
|
2016-07-13 22:09:42 +03:00
|
|
|
|
const updated = this._updateRaw(oldRecord, newRecord, options);
|
|
|
|
|
this.adapterTransaction.update(updated);
|
2016-08-25 21:13:15 +03:00
|
|
|
|
this._queueEvent("update", { data: updated, oldRecord });
|
|
|
|
|
return { data: updated, oldRecord, permissions: {} };
|
2016-07-13 22:09:42 +03:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Lower-level primitive for updating a record while respecting
|
|
|
|
|
* _status and last_modified.
|
|
|
|
|
*
|
|
|
|
|
* @param {Object} oldRecord: the record retrieved from the DB
|
|
|
|
|
* @param {Object} newRecord: the record to replace it with
|
|
|
|
|
* @return {Object}
|
|
|
|
|
*/
|
|
|
|
|
_updateRaw(oldRecord, newRecord, { synced = false } = {}) {
|
2016-11-16 03:38:53 +03:00
|
|
|
|
const updated = _extends({}, newRecord);
|
2016-07-13 22:09:42 +03:00
|
|
|
|
// Make sure to never loose the existing timestamp.
|
|
|
|
|
if (oldRecord && oldRecord.last_modified && !updated.last_modified) {
|
|
|
|
|
updated.last_modified = oldRecord.last_modified;
|
|
|
|
|
}
|
|
|
|
|
// If only local fields have changed, then keep record as synced.
|
|
|
|
|
// If status is created, keep record as created.
|
|
|
|
|
// If status is deleted, mark as updated.
|
|
|
|
|
const isIdentical = oldRecord && recordsEqual(oldRecord, updated, this.localFields);
|
|
|
|
|
const keepSynced = isIdentical && oldRecord._status == "synced";
|
|
|
|
|
const neverSynced = !oldRecord || oldRecord && oldRecord._status == "created";
|
|
|
|
|
const newStatus = keepSynced || synced ? "synced" : neverSynced ? "created" : "updated";
|
|
|
|
|
return markStatus(updated, newStatus);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Upsert a record into the local database.
|
|
|
|
|
*
|
|
|
|
|
* This record must have an ID.
|
|
|
|
|
*
|
|
|
|
|
* If a record with this ID already exists, it will be replaced.
|
|
|
|
|
* Otherwise, this record will be inserted.
|
|
|
|
|
*
|
|
|
|
|
* @param {Object} record
|
|
|
|
|
* @return {Object}
|
|
|
|
|
*/
|
|
|
|
|
upsert(record) {
|
|
|
|
|
if (typeof record !== "object") {
|
|
|
|
|
throw new Error("Record is not an object.");
|
|
|
|
|
}
|
|
|
|
|
if (!record.hasOwnProperty("id")) {
|
|
|
|
|
throw new Error("Cannot update a record missing id.");
|
|
|
|
|
}
|
|
|
|
|
if (!this.collection.idSchema.validate(record.id)) {
|
2017-01-28 03:23:05 +03:00
|
|
|
|
throw new Error(`Invalid Id: ${record.id}`);
|
2016-07-13 22:09:42 +03:00
|
|
|
|
}
|
|
|
|
|
let oldRecord = this.adapterTransaction.get(record.id);
|
|
|
|
|
const updated = this._updateRaw(oldRecord, record);
|
|
|
|
|
this.adapterTransaction.update(updated);
|
|
|
|
|
// Don't return deleted records -- pretend they are gone
|
|
|
|
|
if (oldRecord && oldRecord._status == "deleted") {
|
|
|
|
|
oldRecord = undefined;
|
|
|
|
|
}
|
2016-08-25 21:13:15 +03:00
|
|
|
|
if (oldRecord) {
|
|
|
|
|
this._queueEvent("update", { data: updated, oldRecord });
|
|
|
|
|
} else {
|
|
|
|
|
this._queueEvent("create", { data: updated });
|
|
|
|
|
}
|
|
|
|
|
return { data: updated, oldRecord, permissions: {} };
|
2016-07-13 22:09:42 +03:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
exports.CollectionTransaction = CollectionTransaction;
|
|
|
|
|
|
2016-11-16 03:38:53 +03:00
|
|
|
|
},{"./adapters/IDB":4,"./adapters/base":5,"./utils":7,"uuid":2}],7:[function(require,module,exports){
|
2016-04-15 02:07:31 +03:00
|
|
|
|
"use strict";
|
|
|
|
|
|
|
|
|
|
Object.defineProperty(exports, "__esModule", {
|
|
|
|
|
value: true
|
|
|
|
|
});
|
|
|
|
|
exports.sortObjects = sortObjects;
|
2016-10-07 17:27:48 +03:00
|
|
|
|
exports.filterObject = filterObject;
|
2016-04-15 02:07:31 +03:00
|
|
|
|
exports.filterObjects = filterObjects;
|
|
|
|
|
exports.isUUID = isUUID;
|
|
|
|
|
exports.waterfall = waterfall;
|
2016-05-02 13:45:50 +03:00
|
|
|
|
exports.deepEqual = deepEqual;
|
2016-07-13 22:09:42 +03:00
|
|
|
|
exports.omitKeys = omitKeys;
|
2016-04-15 02:07:31 +03:00
|
|
|
|
const RE_UUID = exports.RE_UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Checks if a value is undefined.
|
|
|
|
|
* @param {Any} value
|
|
|
|
|
* @return {Boolean}
|
|
|
|
|
*/
|
|
|
|
|
function _isUndefined(value) {
|
|
|
|
|
return typeof value === "undefined";
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Sorts records in a list according to a given ordering.
|
|
|
|
|
*
|
|
|
|
|
* @param {String} order The ordering, eg. `-last_modified`.
|
|
|
|
|
* @param {Array} list The collection to order.
|
|
|
|
|
* @return {Array}
|
|
|
|
|
*/
|
|
|
|
|
function sortObjects(order, list) {
|
|
|
|
|
const hasDash = order[0] === "-";
|
|
|
|
|
const field = hasDash ? order.slice(1) : order;
|
|
|
|
|
const direction = hasDash ? -1 : 1;
|
|
|
|
|
return list.slice().sort((a, b) => {
|
|
|
|
|
if (a[field] && _isUndefined(b[field])) {
|
|
|
|
|
return direction;
|
|
|
|
|
}
|
|
|
|
|
if (b[field] && _isUndefined(a[field])) {
|
|
|
|
|
return -direction;
|
|
|
|
|
}
|
|
|
|
|
if (_isUndefined(a[field]) && _isUndefined(b[field])) {
|
|
|
|
|
return 0;
|
|
|
|
|
}
|
|
|
|
|
return a[field] > b[field] ? direction : -direction;
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
2016-10-07 17:27:48 +03:00
|
|
|
|
* Test if a single object matches all given filters.
|
2016-04-15 02:07:31 +03:00
|
|
|
|
*
|
2016-10-07 17:27:48 +03:00
|
|
|
|
* @param {Object} filters The filters object.
|
|
|
|
|
* @param {Object} entry The object to filter.
|
|
|
|
|
* @return {Function}
|
2016-04-15 02:07:31 +03:00
|
|
|
|
*/
|
2016-10-07 17:27:48 +03:00
|
|
|
|
function filterObject(filters, entry) {
|
2016-11-16 03:38:53 +03:00
|
|
|
|
return Object.keys(filters).every(filter => {
|
2016-10-07 17:27:48 +03:00
|
|
|
|
const value = filters[filter];
|
|
|
|
|
if (Array.isArray(value)) {
|
|
|
|
|
return value.some(candidate => candidate === entry[filter]);
|
|
|
|
|
}
|
|
|
|
|
return entry[filter] === value;
|
2016-04-15 02:07:31 +03:00
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
2016-10-07 17:27:48 +03:00
|
|
|
|
* Filters records in a list matching all given filters.
|
2016-04-15 02:07:31 +03:00
|
|
|
|
*
|
2016-10-07 17:27:48 +03:00
|
|
|
|
* @param {Object} filters The filters object.
|
|
|
|
|
* @param {Array} list The collection to filter.
|
2016-04-15 02:07:31 +03:00
|
|
|
|
* @return {Array}
|
|
|
|
|
*/
|
2016-10-07 17:27:48 +03:00
|
|
|
|
function filterObjects(filters, list) {
|
|
|
|
|
return list.filter(entry => {
|
|
|
|
|
return filterObject(filters, entry);
|
|
|
|
|
});
|
2016-04-15 02:07:31 +03:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Checks if a string is an UUID.
|
|
|
|
|
*
|
|
|
|
|
* @param {String} uuid The uuid to validate.
|
|
|
|
|
* @return {Boolean}
|
|
|
|
|
*/
|
|
|
|
|
function isUUID(uuid) {
|
|
|
|
|
return RE_UUID.test(uuid);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Resolves a list of functions sequentially, which can be sync or async; in
|
|
|
|
|
* case of async, functions must return a promise.
|
|
|
|
|
*
|
|
|
|
|
* @param {Array} fns The list of functions.
|
|
|
|
|
* @param {Any} init The initial value.
|
|
|
|
|
* @return {Promise}
|
|
|
|
|
*/
|
|
|
|
|
function waterfall(fns, init) {
|
|
|
|
|
if (!fns.length) {
|
2016-11-16 03:38:53 +03:00
|
|
|
|
return Promise.resolve(init);
|
2016-04-15 02:07:31 +03:00
|
|
|
|
}
|
|
|
|
|
return fns.reduce((promise, nextFn) => {
|
|
|
|
|
return promise.then(nextFn);
|
2016-11-16 03:38:53 +03:00
|
|
|
|
}, Promise.resolve(init));
|
2016-04-15 02:07:31 +03:00
|
|
|
|
}
|
|
|
|
|
|
2016-05-02 13:45:50 +03:00
|
|
|
|
/**
|
|
|
|
|
* Simple deep object comparison function. This only supports comparison of
|
|
|
|
|
* serializable JavaScript objects.
|
|
|
|
|
*
|
|
|
|
|
* @param {Object} a The source object.
|
|
|
|
|
* @param {Object} b The compared object.
|
|
|
|
|
* @return {Boolean}
|
|
|
|
|
*/
|
|
|
|
|
function deepEqual(a, b) {
|
|
|
|
|
if (a === b) {
|
|
|
|
|
return true;
|
|
|
|
|
}
|
|
|
|
|
if (typeof a !== typeof b) {
|
|
|
|
|
return false;
|
|
|
|
|
}
|
2016-08-30 19:19:19 +03:00
|
|
|
|
if (!(a && typeof a == "object") || !(b && typeof b == "object")) {
|
2016-05-02 13:45:50 +03:00
|
|
|
|
return false;
|
|
|
|
|
}
|
2016-11-16 03:38:53 +03:00
|
|
|
|
if (Object.keys(a).length !== Object.keys(b).length) {
|
2016-05-02 13:45:50 +03:00
|
|
|
|
return false;
|
|
|
|
|
}
|
|
|
|
|
for (let k in a) {
|
|
|
|
|
if (!deepEqual(a[k], b[k])) {
|
|
|
|
|
return false;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
return true;
|
|
|
|
|
}
|
|
|
|
|
|
2016-07-13 22:09:42 +03:00
|
|
|
|
/**
|
|
|
|
|
* Return an object without the specified keys.
|
|
|
|
|
*
|
|
|
|
|
* @param {Object} obj The original object.
|
|
|
|
|
* @param {Array} keys The list of keys to exclude.
|
|
|
|
|
* @return {Object} A copy without the specified keys.
|
|
|
|
|
*/
|
|
|
|
|
function omitKeys(obj, keys = []) {
|
2016-11-16 03:38:53 +03:00
|
|
|
|
return Object.keys(obj).reduce((acc, key) => {
|
2016-07-13 22:09:42 +03:00
|
|
|
|
if (keys.indexOf(key) === -1) {
|
|
|
|
|
acc[key] = obj[key];
|
|
|
|
|
}
|
|
|
|
|
return acc;
|
|
|
|
|
}, {});
|
|
|
|
|
}
|
|
|
|
|
|
2016-11-16 03:38:53 +03:00
|
|
|
|
},{}]},{},[1])(1)
|
2017-01-28 03:23:05 +03:00
|
|
|
|
});
|