2016-05-03 22:50:21 +00:00
|
|
|
// Copyright IBM Corp. 2014,2016. All Rights Reserved.
|
|
|
|
// Node module: loopback
|
|
|
|
// This file is licensed under the MIT License.
|
|
|
|
// License text available at https://opensource.org/licenses/MIT
|
|
|
|
|
2014-02-20 01:09:36 +00:00
|
|
|
/*!
|
|
|
|
* Module Dependencies.
|
|
|
|
*/
|
2016-11-15 21:46:23 +00:00
|
|
|
'use strict';
|
2016-09-16 19:31:48 +00:00
|
|
|
var g = require('./globalize');
|
2014-10-09 15:32:03 +00:00
|
|
|
var runtime = require('./runtime');
|
2014-05-06 20:31:23 +00:00
|
|
|
var assert = require('assert');
|
|
|
|
var async = require('async');
|
2015-02-26 15:29:29 +00:00
|
|
|
var deprecated = require('depd')('loopback');
|
2015-03-04 14:00:53 +00:00
|
|
|
var debug = require('debug')('loopback:persisted-model');
|
2015-07-09 20:30:50 +00:00
|
|
|
var PassThrough = require('stream').PassThrough;
|
2015-07-20 12:00:05 +00:00
|
|
|
var utils = require('./utils');
|
2016-11-21 08:48:43 +00:00
|
|
|
var REPLICATION_CHUNK_SIZE = -1;
|
2014-02-20 01:09:36 +00:00
|
|
|
|
2015-04-03 07:26:19 +00:00
|
|
|
module.exports = function(registry) {
|
2015-04-01 21:50:36 +00:00
|
|
|
var Model = registry.getModel('Model');
|
2015-04-03 07:26:19 +00:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Extends Model with basic query and CRUD support.
|
|
|
|
*
|
|
|
|
* **Change Event**
|
|
|
|
*
|
|
|
|
* Listen for model changes using the `change` event.
|
|
|
|
*
|
|
|
|
* ```js
|
|
|
|
* MyPersistedModel.on('changed', function(obj) {
|
|
|
|
* console.log(obj) // => the changed model
|
|
|
|
* });
|
|
|
|
* ```
|
|
|
|
*
|
|
|
|
* @class PersistedModel
|
|
|
|
*/
|
|
|
|
|
|
|
|
var PersistedModel = Model.extend('PersistedModel');
|
|
|
|
|
|
|
|
/*!
|
|
|
|
* Setup the `PersistedModel` constructor.
|
|
|
|
*/
|
|
|
|
|
|
|
|
PersistedModel.setup = function setupPersistedModel() {
|
|
|
|
// call Model.setup first
|
|
|
|
Model.setup.call(this);
|
|
|
|
|
|
|
|
var PersistedModel = this;
|
|
|
|
|
|
|
|
// enable change tracking (usually for replication)
|
|
|
|
if (this.settings.trackChanges) {
|
|
|
|
PersistedModel._defineChangeModel();
|
|
|
|
PersistedModel.once('dataSourceAttached', function() {
|
|
|
|
PersistedModel.enableChangeTracking();
|
|
|
|
});
|
2015-04-03 14:41:32 +00:00
|
|
|
} else if (this.settings.enableRemoteReplication) {
|
|
|
|
PersistedModel._defineChangeModel();
|
2015-04-03 07:26:19 +00:00
|
|
|
}
|
2014-05-03 01:12:24 +00:00
|
|
|
|
2015-04-03 07:26:19 +00:00
|
|
|
PersistedModel.setupRemoting();
|
|
|
|
};
|
2014-05-03 03:04:06 +00:00
|
|
|
|
2015-04-03 07:26:19 +00:00
|
|
|
/*!
|
|
|
|
* Throw an error telling the user that the method is not available and why.
|
|
|
|
*/
|
2014-05-03 01:12:24 +00:00
|
|
|
|
2015-04-03 07:26:19 +00:00
|
|
|
function throwNotAttached(modelName, methodName) {
|
|
|
|
throw new Error(
|
2016-06-07 14:48:28 +00:00
|
|
|
g.f('Cannot call %s.%s().' +
|
|
|
|
' The %s method has not been setup.' +
|
|
|
|
' The {{PersistedModel}} has not been correctly attached to a {{DataSource}}!',
|
|
|
|
modelName, methodName, methodName)
|
2015-04-03 07:26:19 +00:00
|
|
|
);
|
2014-05-06 20:31:23 +00:00
|
|
|
}
|
2014-10-16 22:54:40 +00:00
|
|
|
|
2015-04-03 07:26:19 +00:00
|
|
|
/*!
|
|
|
|
* Convert null callbacks to 404 error objects.
|
|
|
|
* @param {HttpContext} ctx
|
|
|
|
* @param {Function} cb
|
|
|
|
*/
|
|
|
|
|
|
|
|
function convertNullToNotFoundError(ctx, cb) {
|
|
|
|
if (ctx.result !== null) return cb();
|
|
|
|
|
|
|
|
var modelName = ctx.method.sharedClass.name;
|
|
|
|
var id = ctx.getArgByName('id');
|
2016-08-04 21:26:01 +00:00
|
|
|
var msg = g.f('Unknown "%s" {{id}} "%s".', modelName, id);
|
2015-04-03 07:26:19 +00:00
|
|
|
var error = new Error(msg);
|
|
|
|
error.statusCode = error.status = 404;
|
|
|
|
error.code = 'MODEL_NOT_FOUND';
|
|
|
|
cb(error);
|
|
|
|
}
|
2014-02-20 01:09:36 +00:00
|
|
|
|
2015-04-03 07:26:19 +00:00
|
|
|
/**
|
|
|
|
* Create new instance of Model, and save to database.
|
|
|
|
*
|
2016-04-01 18:00:01 +00:00
|
|
|
* @param {Object|Object[]} [data] Optional data argument. Can be either a single model instance or an array of instances.
|
2015-04-03 07:26:19 +00:00
|
|
|
*
|
|
|
|
* @callback {Function} callback Callback function called with `cb(err, obj)` signature.
|
2016-11-04 20:47:12 +00:00
|
|
|
* @param {Error} err Error object; see [Error object](http://loopback.io/doc/en/lb2/Error-object.html).
|
2015-04-03 07:26:19 +00:00
|
|
|
* @param {Object} models Model instances or null.
|
|
|
|
*/
|
|
|
|
|
|
|
|
PersistedModel.create = function(data, callback) {
|
|
|
|
throwNotAttached(this.modelName, 'create');
|
|
|
|
};
|
2014-02-20 01:09:36 +00:00
|
|
|
|
2015-04-03 07:26:19 +00:00
|
|
|
/**
|
|
|
|
* Update or insert a model instance
|
|
|
|
* @param {Object} data The model instance data to insert.
|
|
|
|
* @callback {Function} callback Callback function called with `cb(err, obj)` signature.
|
2016-11-04 20:47:12 +00:00
|
|
|
* @param {Error} err Error object; see [Error object](http://loopback.io/doc/en/lb2/Error-object.html).
|
2015-04-03 07:26:19 +00:00
|
|
|
* @param {Object} model Updated model instance.
|
|
|
|
*/
|
2014-02-20 01:09:36 +00:00
|
|
|
|
2016-05-09 19:24:03 +00:00
|
|
|
PersistedModel.upsert = PersistedModel.updateOrCreate = PersistedModel.patchOrCreate =
|
|
|
|
function upsert(data, callback) {
|
2015-04-03 07:26:19 +00:00
|
|
|
throwNotAttached(this.modelName, 'upsert');
|
|
|
|
};
|
2014-02-20 01:09:36 +00:00
|
|
|
|
2016-09-02 12:40:47 +00:00
|
|
|
/**
|
|
|
|
* Update or insert a model instance based on the search criteria.
|
|
|
|
* If there is a single instance retrieved, update the retrieved model.
|
|
|
|
* Creates a new model if no model instances were found.
|
|
|
|
* Returns an error if multiple instances are found.
|
2016-11-24 20:58:21 +00:00
|
|
|
* @param {Object} [where] `where` filter, like
|
2016-09-02 12:40:47 +00:00
|
|
|
* ```
|
|
|
|
* { key: val, key2: {gt: 'val2'}, ...}
|
|
|
|
* ```
|
|
|
|
* <br/>see
|
2016-11-04 20:47:12 +00:00
|
|
|
* [Where filter](http://loopback.io/doc/en/lb2/Where-filter.html#where-clause-for-other-methods).
|
2016-09-02 12:40:47 +00:00
|
|
|
* @param {Object} data The model instance data to insert.
|
|
|
|
* @callback {Function} callback Callback function called with `cb(err, obj)` signature.
|
2016-11-04 20:47:12 +00:00
|
|
|
* @param {Error} err Error object; see [Error object](http://loopback.io/doc/en/lb2/Error-object.html).
|
2016-09-02 12:40:47 +00:00
|
|
|
* @param {Object} model Updated model instance.
|
|
|
|
*/
|
|
|
|
|
|
|
|
PersistedModel.upsertWithWhere =
|
|
|
|
PersistedModel.patchOrCreateWithWhere = function upsertWithWhere(where, data, callback) {
|
|
|
|
throwNotAttached(this.modelName, 'upsertWithWhere');
|
|
|
|
};
|
|
|
|
|
2016-05-20 19:21:00 +00:00
|
|
|
/**
|
|
|
|
* Replace or insert a model instance; replace existing record if one is found,
|
|
|
|
* such that parameter `data.id` matches `id` of model instance; otherwise,
|
|
|
|
* insert a new record.
|
|
|
|
* @param {Object} data The model instance data.
|
|
|
|
* @options {Object} [options] Options for replaceOrCreate
|
|
|
|
* @property {Boolean} validate Perform validation before saving. Default is true.
|
|
|
|
* @callback {Function} callback Callback function called with `cb(err, obj)` signature.
|
2016-11-04 20:47:12 +00:00
|
|
|
* @param {Error} err Error object; see [Error object](http://loopback.io/doc/en/lb2/Error-object.html).
|
2016-05-20 19:21:00 +00:00
|
|
|
* @param {Object} model Replaced model instance.
|
|
|
|
*/
|
|
|
|
|
|
|
|
PersistedModel.replaceOrCreate = function replaceOrCreate(data, callback) {
|
|
|
|
throwNotAttached(this.modelName, 'replaceOrCreate');
|
|
|
|
};
|
|
|
|
|
2015-04-03 07:26:19 +00:00
|
|
|
/**
|
2015-12-31 22:04:09 +00:00
|
|
|
* Finds one record matching the optional filter object. If not found, creates
|
|
|
|
* the object using the data provided as second argument. In this sense it is
|
|
|
|
* the same as `find`, but limited to one object. Returns an object, not
|
|
|
|
* collection. If you don't provide the filter object argument, it tries to
|
|
|
|
* locate an existing object that matches the `data` argument.
|
2015-04-03 07:26:19 +00:00
|
|
|
*
|
2015-12-23 00:35:33 +00:00
|
|
|
* @options {Object} [filter] Optional Filter object; see below.
|
|
|
|
* @property {String|Object|Array} fields Identify fields to include in return result.
|
2016-11-04 20:47:12 +00:00
|
|
|
* <br/>See [Fields filter](http://loopback.io/doc/en/lb2/Fields-filter.html).
|
2015-12-23 00:35:33 +00:00
|
|
|
* @property {String|Object|Array} include See PersistedModel.include documentation.
|
2016-11-04 20:47:12 +00:00
|
|
|
* <br/>See [Include filter](http://loopback.io/doc/en/lb2/Include-filter.html).
|
2015-12-23 00:35:33 +00:00
|
|
|
* @property {Number} limit Maximum number of instances to return.
|
2016-11-04 20:47:12 +00:00
|
|
|
* <br/>See [Limit filter](http://loopback.io/doc/en/lb2/Limit-filter.html).
|
2015-12-23 00:35:33 +00:00
|
|
|
* @property {String} order Sort order: either "ASC" for ascending or "DESC" for descending.
|
2016-11-04 20:47:12 +00:00
|
|
|
* <br/>See [Order filter](http://loopback.io/doc/en/lb2/Order-filter.html).
|
2015-12-23 00:35:33 +00:00
|
|
|
* @property {Number} skip Number of results to skip.
|
2016-11-04 20:47:12 +00:00
|
|
|
* <br/>See [Skip filter](http://loopback.io/doc/en/lb2/Skip-filter.html).
|
2015-12-23 00:35:33 +00:00
|
|
|
* @property {Object} where Where clause, like
|
|
|
|
* ```
|
|
|
|
* {where: {key: val, key2: {gt: val2}, ...}}
|
|
|
|
* ```
|
|
|
|
* <br/>See
|
2016-11-04 20:47:12 +00:00
|
|
|
* [Where filter](http://loopback.io/doc/en/lb2/Where-filter.html#where-clause-for-queries).
|
2015-04-03 07:26:19 +00:00
|
|
|
* @param {Object} data Data to insert if object matching the `where` filter is not found.
|
2016-01-22 03:40:19 +00:00
|
|
|
* @callback {Function} callback Callback function called with `cb(err, instance, created)` arguments. Required.
|
2016-11-04 20:47:12 +00:00
|
|
|
* @param {Error} err Error object; see [Error object](http://loopback.io/doc/en/lb2/Error-object.html).
|
2015-04-03 07:26:19 +00:00
|
|
|
* @param {Object} instance Model instance matching the `where` filter, if found.
|
2016-05-17 21:50:13 +00:00
|
|
|
* @param {Boolean} created True if the instance does not exist and gets created.
|
2015-04-03 07:26:19 +00:00
|
|
|
*/
|
|
|
|
|
|
|
|
PersistedModel.findOrCreate = function findOrCreate(query, data, callback) {
|
|
|
|
throwNotAttached(this.modelName, 'findOrCreate');
|
|
|
|
};
|
2014-02-20 01:09:36 +00:00
|
|
|
|
2015-04-03 07:26:19 +00:00
|
|
|
PersistedModel.findOrCreate._delegate = true;
|
2014-02-20 01:09:36 +00:00
|
|
|
|
2015-04-03 07:26:19 +00:00
|
|
|
/**
|
|
|
|
* Check whether a model instance exists in database.
|
|
|
|
*
|
|
|
|
* @param {id} id Identifier of object (primary key value).
|
|
|
|
*
|
|
|
|
* @callback {Function} callback Callback function called with `(err, exists)` arguments. Required.
|
2016-11-04 20:47:12 +00:00
|
|
|
* @param {Error} err Error object; see [Error object](http://loopback.io/doc/en/lb2/Error-object.html).
|
2015-04-03 07:26:19 +00:00
|
|
|
* @param {Boolean} exists True if the instance with the specified ID exists; false otherwise.
|
|
|
|
*/
|
2014-10-15 07:07:30 +00:00
|
|
|
|
2015-04-03 07:26:19 +00:00
|
|
|
PersistedModel.exists = function exists(id, cb) {
|
|
|
|
throwNotAttached(this.modelName, 'exists');
|
|
|
|
};
|
2014-10-15 07:07:30 +00:00
|
|
|
|
2015-04-03 07:26:19 +00:00
|
|
|
/**
|
2015-04-16 22:02:41 +00:00
|
|
|
* Find object by ID with an optional filter for include/fields.
|
2015-04-03 07:26:19 +00:00
|
|
|
*
|
|
|
|
* @param {*} id Primary key value
|
2015-04-16 22:02:41 +00:00
|
|
|
* @options {Object} [filter] Optional Filter JSON object; see below.
|
|
|
|
* @property {String|Object|Array} fields Identify fields to include in return result.
|
2016-11-04 20:47:12 +00:00
|
|
|
* <br/>See [Fields filter](http://loopback.io/doc/en/lb2/Fields-filter.html).
|
2015-04-16 22:02:41 +00:00
|
|
|
* @property {String|Object|Array} include See PersistedModel.include documentation.
|
2016-11-04 20:47:12 +00:00
|
|
|
* <br/>See [Include filter](http://loopback.io/doc/en/lb2/Include-filter.html).
|
2015-04-03 07:26:19 +00:00
|
|
|
* @callback {Function} callback Callback function called with `(err, instance)` arguments. Required.
|
2016-11-04 20:47:12 +00:00
|
|
|
* @param {Error} err Error object; see [Error object](http://loopback.io/doc/en/lb2/Error-object.html).
|
2015-04-03 07:26:19 +00:00
|
|
|
* @param {Object} instance Model instance matching the specified ID or null if no instance matches.
|
|
|
|
*/
|
|
|
|
|
2015-10-28 04:48:36 +00:00
|
|
|
PersistedModel.findById = function findById(id, filter, cb) {
|
2015-04-03 07:26:19 +00:00
|
|
|
throwNotAttached(this.modelName, 'findById');
|
|
|
|
};
|
2014-06-21 06:08:35 +00:00
|
|
|
|
2015-04-03 07:26:19 +00:00
|
|
|
/**
|
|
|
|
* Find all model instances that match `filter` specification.
|
2016-11-04 20:47:12 +00:00
|
|
|
* See [Querying models](http://loopback.io/doc/en/lb2/Querying-data.html).
|
2015-04-03 07:26:19 +00:00
|
|
|
*
|
|
|
|
* @options {Object} [filter] Optional Filter JSON object; see below.
|
|
|
|
* @property {String|Object|Array} fields Identify fields to include in return result.
|
2016-11-04 20:47:12 +00:00
|
|
|
* <br/>See [Fields filter](http://loopback.io/doc/en/lb2/Fields-filter.html).
|
2015-04-03 07:26:19 +00:00
|
|
|
* @property {String|Object|Array} include See PersistedModel.include documentation.
|
2016-11-04 20:47:12 +00:00
|
|
|
* <br/>See [Include filter](http://loopback.io/doc/en/lb2/Include-filter.html).
|
2015-04-03 07:26:19 +00:00
|
|
|
* @property {Number} limit Maximum number of instances to return.
|
2016-11-04 20:47:12 +00:00
|
|
|
* <br/>See [Limit filter](http://loopback.io/doc/en/lb2/Limit-filter.html).
|
2015-04-03 07:26:19 +00:00
|
|
|
* @property {String} order Sort order: either "ASC" for ascending or "DESC" for descending.
|
2016-11-04 20:47:12 +00:00
|
|
|
* <br/>See [Order filter](http://loopback.io/doc/en/lb2/Order-filter.html).
|
2015-04-03 07:26:19 +00:00
|
|
|
* @property {Number} skip Number of results to skip.
|
2016-11-04 20:47:12 +00:00
|
|
|
* <br/>See [Skip filter](http://loopback.io/doc/en/lb2/Skip-filter.html).
|
2015-04-03 07:26:19 +00:00
|
|
|
* @property {Object} where Where clause, like
|
|
|
|
* ```
|
|
|
|
* { where: { key: val, key2: {gt: 'val2'}, ...} }
|
|
|
|
* ```
|
2015-09-09 23:08:20 +00:00
|
|
|
* <br/>See
|
2016-11-04 20:47:12 +00:00
|
|
|
* [Where filter](http://loopback.io/doc/en/lb2/Where-filter.html#where-clause-for-queries).
|
2015-04-03 07:26:19 +00:00
|
|
|
*
|
|
|
|
* @callback {Function} callback Callback function called with `(err, returned-instances)` arguments. Required.
|
2016-11-04 20:47:12 +00:00
|
|
|
* @param {Error} err Error object; see [Error object](http://loopback.io/doc/en/lb2/Error-object.html).
|
2015-04-03 07:26:19 +00:00
|
|
|
* @param {Array} models Model instances matching the filter, or null if none found.
|
|
|
|
*/
|
|
|
|
|
2015-04-16 22:02:41 +00:00
|
|
|
PersistedModel.find = function find(filter, cb) {
|
2015-04-03 07:26:19 +00:00
|
|
|
throwNotAttached(this.modelName, 'find');
|
|
|
|
};
|
2014-02-20 01:09:36 +00:00
|
|
|
|
2015-04-03 07:26:19 +00:00
|
|
|
/**
|
|
|
|
* Find one model instance that matches `filter` specification.
|
|
|
|
* Same as `find`, but limited to one result;
|
|
|
|
* Returns object, not collection.
|
|
|
|
*
|
|
|
|
* @options {Object} [filter] Optional Filter JSON object; see below.
|
|
|
|
* @property {String|Object|Array} fields Identify fields to include in return result.
|
2016-11-04 20:47:12 +00:00
|
|
|
* <br/>See [Fields filter](http://loopback.io/doc/en/lb2/Fields-filter.html).
|
2015-04-03 07:26:19 +00:00
|
|
|
* @property {String|Object|Array} include See PersistedModel.include documentation.
|
2016-11-04 20:47:12 +00:00
|
|
|
* <br/>See [Include filter](http://loopback.io/doc/en/lb2/Include-filter.html).
|
2015-04-03 07:26:19 +00:00
|
|
|
* @property {String} order Sort order: either "ASC" for ascending or "DESC" for descending.
|
2016-11-04 20:47:12 +00:00
|
|
|
* <br/>See [Order filter](http://loopback.io/doc/en/lb2/Order-filter.html).
|
2015-04-03 07:26:19 +00:00
|
|
|
* @property {Number} skip Number of results to skip.
|
2016-11-04 20:47:12 +00:00
|
|
|
* <br/>See [Skip filter](http://loopback.io/doc/en/lb2/Skip-filter.html).
|
2015-04-03 07:26:19 +00:00
|
|
|
* @property {Object} where Where clause, like
|
|
|
|
* ```
|
|
|
|
* {where: { key: val, key2: {gt: 'val2'}, ...} }
|
|
|
|
* ```
|
2015-09-09 23:08:20 +00:00
|
|
|
* <br/>See
|
2016-11-04 20:47:12 +00:00
|
|
|
* [Where filter](http://loopback.io/doc/en/lb2/Where-filter.html#where-clause-for-queries).
|
2015-04-03 07:26:19 +00:00
|
|
|
*
|
|
|
|
* @callback {Function} callback Callback function called with `(err, returned-instance)` arguments. Required.
|
2016-11-04 20:47:12 +00:00
|
|
|
* @param {Error} err Error object; see [Error object](http://loopback.io/doc/en/lb2/Error-object.html).
|
2015-04-03 07:26:19 +00:00
|
|
|
* @param {Array} model First model instance that matches the filter or null if none found.
|
|
|
|
*/
|
|
|
|
|
2015-04-16 22:02:41 +00:00
|
|
|
PersistedModel.findOne = function findOne(filter, cb) {
|
2015-04-03 07:26:19 +00:00
|
|
|
throwNotAttached(this.modelName, 'findOne');
|
|
|
|
};
|
2014-10-15 07:07:30 +00:00
|
|
|
|
2015-04-03 07:26:19 +00:00
|
|
|
/**
|
|
|
|
* Destroy all model instances that match the optional `where` specification.
|
|
|
|
*
|
|
|
|
* @param {Object} [where] Optional where filter, like:
|
|
|
|
* ```
|
2015-07-28 15:29:43 +00:00
|
|
|
* {key: val, key2: {gt: 'val2'}, ...}
|
2015-04-03 07:26:19 +00:00
|
|
|
* ```
|
2015-09-09 23:08:20 +00:00
|
|
|
* <br/>See
|
2016-11-04 20:47:12 +00:00
|
|
|
* [Where filter](http://loopback.io/doc/en/lb2/Where-filter.html#where-clause-for-other-methods).
|
2015-04-03 07:26:19 +00:00
|
|
|
*
|
|
|
|
* @callback {Function} callback Optional callback function called with `(err, info)` arguments.
|
2016-11-04 20:47:12 +00:00
|
|
|
* @param {Error} err Error object; see [Error object](http://loopback.io/doc/en/lb2/Error-object.html).
|
2015-04-03 07:26:19 +00:00
|
|
|
* @param {Object} info Additional information about the command outcome.
|
|
|
|
* @param {Number} info.count Number of instances (rows, documents) destroyed.
|
|
|
|
*/
|
|
|
|
|
|
|
|
PersistedModel.destroyAll = function destroyAll(where, cb) {
|
|
|
|
throwNotAttached(this.modelName, 'destroyAll');
|
|
|
|
};
|
2014-02-20 01:09:36 +00:00
|
|
|
|
2015-04-03 07:26:19 +00:00
|
|
|
/**
|
|
|
|
* Alias for `destroyAll`
|
|
|
|
*/
|
|
|
|
PersistedModel.remove = PersistedModel.destroyAll;
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Alias for `destroyAll`
|
|
|
|
*/
|
|
|
|
PersistedModel.deleteAll = PersistedModel.destroyAll;
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Update multiple instances that match the where clause.
|
|
|
|
*
|
|
|
|
* Example:
|
|
|
|
*
|
|
|
|
*```js
|
|
|
|
* Employee.updateAll({managerId: 'x001'}, {managerId: 'x002'}, function(err, info) {
|
|
|
|
* ...
|
|
|
|
* });
|
|
|
|
* ```
|
|
|
|
*
|
|
|
|
* @param {Object} [where] Optional `where` filter, like
|
|
|
|
* ```
|
2015-07-28 15:29:43 +00:00
|
|
|
* { key: val, key2: {gt: 'val2'}, ...}
|
2015-04-03 07:26:19 +00:00
|
|
|
* ```
|
2015-09-09 23:08:20 +00:00
|
|
|
* <br/>see
|
2016-11-04 20:47:12 +00:00
|
|
|
* [Where filter](http://loopback.io/doc/en/lb2/Where-filter.html#where-clause-for-other-methods).
|
2015-04-03 07:26:19 +00:00
|
|
|
* @param {Object} data Object containing data to replace matching instances, if any.
|
|
|
|
*
|
|
|
|
* @callback {Function} callback Callback function called with `(err, info)` arguments. Required.
|
2016-11-04 20:47:12 +00:00
|
|
|
* @param {Error} err Error object; see [Error object](http://loopback.io/doc/en/lb2/Error-object.html).
|
2015-04-03 07:26:19 +00:00
|
|
|
* @param {Object} info Additional information about the command outcome.
|
|
|
|
* @param {Number} info.count Number of instances (rows, documents) updated.
|
|
|
|
*
|
|
|
|
*/
|
|
|
|
PersistedModel.updateAll = function updateAll(where, data, cb) {
|
|
|
|
throwNotAttached(this.modelName, 'updateAll');
|
|
|
|
};
|
2014-02-20 01:09:36 +00:00
|
|
|
|
2015-04-03 07:26:19 +00:00
|
|
|
/**
|
|
|
|
* Alias for updateAll.
|
|
|
|
*/
|
|
|
|
PersistedModel.update = PersistedModel.updateAll;
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Destroy model instance with the specified ID.
|
|
|
|
* @param {*} id The ID value of model instance to delete.
|
|
|
|
* @callback {Function} callback Callback function called with `(err)` arguments. Required.
|
2016-11-04 20:47:12 +00:00
|
|
|
* @param {Error} err Error object; see [Error object](http://loopback.io/doc/en/lb2/Error-object.html).
|
2015-04-03 07:26:19 +00:00
|
|
|
*/
|
|
|
|
PersistedModel.destroyById = function deleteById(id, cb) {
|
|
|
|
throwNotAttached(this.modelName, 'deleteById');
|
|
|
|
};
|
2014-02-20 01:09:36 +00:00
|
|
|
|
2015-04-03 07:26:19 +00:00
|
|
|
/**
|
|
|
|
* Alias for destroyById.
|
|
|
|
*/
|
|
|
|
PersistedModel.removeById = PersistedModel.destroyById;
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Alias for destroyById.
|
|
|
|
*/
|
|
|
|
PersistedModel.deleteById = PersistedModel.destroyById;
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Return the number of records that match the optional "where" filter.
|
|
|
|
* @param {Object} [where] Optional where filter, like
|
|
|
|
* ```
|
2015-07-28 15:29:43 +00:00
|
|
|
* { key: val, key2: {gt: 'val2'}, ...}
|
2015-04-03 07:26:19 +00:00
|
|
|
* ```
|
2015-09-09 23:08:20 +00:00
|
|
|
* <br/>See
|
2016-11-04 20:47:12 +00:00
|
|
|
* [Where filter](http://loopback.io/doc/en/lb2/Where-filter.html#where-clause-for-other-methods).
|
2015-04-03 07:26:19 +00:00
|
|
|
* @callback {Function} callback Callback function called with `(err, count)` arguments. Required.
|
2016-11-04 20:47:12 +00:00
|
|
|
* @param {Error} err Error object; see [Error object](http://loopback.io/doc/en/lb2/Error-object.html).
|
2017-01-03 17:31:23 +00:00
|
|
|
* @param {Number} count Number of instances.
|
2015-04-03 07:26:19 +00:00
|
|
|
*/
|
|
|
|
|
|
|
|
PersistedModel.count = function(where, cb) {
|
|
|
|
throwNotAttached(this.modelName, 'count');
|
|
|
|
};
|
2014-05-06 20:31:23 +00:00
|
|
|
|
2015-04-03 07:26:19 +00:00
|
|
|
/**
|
|
|
|
* Save model instance. If the instance doesn't have an ID, then calls [create](#persistedmodelcreatedata-cb) instead.
|
|
|
|
* Triggers: validate, save, update, or create.
|
|
|
|
* @options {Object} [options] See below.
|
|
|
|
* @property {Boolean} validate Perform validation before saving. Default is true.
|
|
|
|
* @property {Boolean} throws If true, throw a validation error; WARNING: This can crash Node.
|
|
|
|
* If false, report the error via callback. Default is false.
|
|
|
|
* @callback {Function} callback Optional callback function called with `(err, obj)` arguments.
|
2016-11-04 20:47:12 +00:00
|
|
|
* @param {Error} err Error object; see [Error object](http://loopback.io/doc/en/lb2/Error-object.html).
|
2015-04-03 07:26:19 +00:00
|
|
|
* @param {Object} instance Model instance saved or created.
|
|
|
|
*/
|
|
|
|
|
|
|
|
PersistedModel.prototype.save = function(options, callback) {
|
|
|
|
var Model = this.constructor;
|
|
|
|
|
|
|
|
if (typeof options == 'function') {
|
|
|
|
callback = options;
|
|
|
|
options = {};
|
|
|
|
}
|
2014-05-06 20:31:23 +00:00
|
|
|
|
2015-04-03 07:26:19 +00:00
|
|
|
callback = callback || function() {
|
|
|
|
};
|
|
|
|
options = options || {};
|
2014-05-06 20:31:23 +00:00
|
|
|
|
2015-04-03 07:26:19 +00:00
|
|
|
if (!('validate' in options)) {
|
|
|
|
options.validate = true;
|
|
|
|
}
|
|
|
|
if (!('throws' in options)) {
|
|
|
|
options.throws = false;
|
|
|
|
}
|
2014-05-06 20:31:23 +00:00
|
|
|
|
2015-04-03 07:26:19 +00:00
|
|
|
var inst = this;
|
|
|
|
var data = inst.toObject(true);
|
|
|
|
var id = this.getId();
|
2014-05-06 20:31:23 +00:00
|
|
|
|
2015-04-03 07:26:19 +00:00
|
|
|
if (!id) {
|
|
|
|
return Model.create(this, callback);
|
|
|
|
}
|
2014-05-06 20:31:23 +00:00
|
|
|
|
2015-04-03 07:26:19 +00:00
|
|
|
// validate first
|
|
|
|
if (!options.validate) {
|
|
|
|
return save();
|
|
|
|
}
|
2014-05-06 20:31:23 +00:00
|
|
|
|
2015-04-03 07:26:19 +00:00
|
|
|
inst.isValid(function(valid) {
|
|
|
|
if (valid) {
|
|
|
|
save();
|
|
|
|
} else {
|
|
|
|
var err = new Model.ValidationError(inst);
|
|
|
|
// throws option is dangerous for async usage
|
|
|
|
if (options.throws) {
|
|
|
|
throw err;
|
|
|
|
}
|
|
|
|
callback(err, inst);
|
2014-05-06 20:31:23 +00:00
|
|
|
}
|
2015-04-03 07:26:19 +00:00
|
|
|
});
|
|
|
|
|
|
|
|
// then save
|
|
|
|
function save() {
|
|
|
|
inst.trigger('save', function(saveDone) {
|
|
|
|
inst.trigger('update', function(updateDone) {
|
|
|
|
Model.upsert(inst, function(err) {
|
|
|
|
inst._initProperties(data);
|
|
|
|
updateDone.call(inst, function() {
|
|
|
|
saveDone.call(inst, function() {
|
|
|
|
callback(err, inst);
|
|
|
|
});
|
2014-05-06 20:31:23 +00:00
|
|
|
});
|
|
|
|
});
|
2015-04-03 07:26:19 +00:00
|
|
|
}, data);
|
2014-05-06 20:31:23 +00:00
|
|
|
}, data);
|
2015-04-03 07:26:19 +00:00
|
|
|
}
|
|
|
|
};
|
2014-02-20 01:09:36 +00:00
|
|
|
|
2015-04-03 07:26:19 +00:00
|
|
|
/**
|
|
|
|
* Determine if the data model is new.
|
|
|
|
* @returns {Boolean} Returns true if the data model is new; false otherwise.
|
|
|
|
*/
|
2014-02-20 01:09:36 +00:00
|
|
|
|
2015-04-03 07:26:19 +00:00
|
|
|
PersistedModel.prototype.isNewRecord = function() {
|
|
|
|
throwNotAttached(this.constructor.modelName, 'isNewRecord');
|
|
|
|
};
|
2014-02-20 01:09:36 +00:00
|
|
|
|
2015-04-03 07:26:19 +00:00
|
|
|
/**
|
|
|
|
* Deletes the model from persistence.
|
|
|
|
* Triggers `destroy` hook (async) before and after destroying object.
|
|
|
|
* @param {Function} callback Callback function.
|
|
|
|
*/
|
2014-10-15 07:07:30 +00:00
|
|
|
|
2015-04-03 07:26:19 +00:00
|
|
|
PersistedModel.prototype.destroy = function(cb) {
|
|
|
|
throwNotAttached(this.constructor.modelName, 'destroy');
|
|
|
|
};
|
2014-02-20 01:09:36 +00:00
|
|
|
|
2015-04-03 07:26:19 +00:00
|
|
|
/**
|
|
|
|
* Alias for destroy.
|
|
|
|
* @header PersistedModel.remove
|
|
|
|
*/
|
|
|
|
PersistedModel.prototype.remove = PersistedModel.prototype.destroy;
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Alias for destroy.
|
|
|
|
* @header PersistedModel.delete
|
|
|
|
*/
|
|
|
|
PersistedModel.prototype.delete = PersistedModel.prototype.destroy;
|
|
|
|
|
|
|
|
PersistedModel.prototype.destroy._delegate = true;
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Update a single attribute.
|
|
|
|
* Equivalent to `updateAttributes({name: 'value'}, cb)`
|
|
|
|
*
|
|
|
|
* @param {String} name Name of property.
|
|
|
|
* @param {Mixed} value Value of property.
|
|
|
|
* @callback {Function} callback Callback function called with `(err, instance)` arguments. Required.
|
2016-11-04 20:47:12 +00:00
|
|
|
* @param {Error} err Error object; see [Error object](http://loopback.io/doc/en/lb2/Error-object.html).
|
2015-04-03 07:26:19 +00:00
|
|
|
* @param {Object} instance Updated instance.
|
|
|
|
*/
|
|
|
|
|
|
|
|
PersistedModel.prototype.updateAttribute = function updateAttribute(name, value, callback) {
|
|
|
|
throwNotAttached(this.constructor.modelName, 'updateAttribute');
|
|
|
|
};
|
2014-02-20 01:09:36 +00:00
|
|
|
|
2015-04-03 07:26:19 +00:00
|
|
|
/**
|
|
|
|
* Update set of attributes. Performs validation before updating.
|
|
|
|
*
|
|
|
|
* Triggers: `validation`, `save` and `update` hooks
|
2015-11-11 21:54:21 +00:00
|
|
|
* @param {Object} data Data to update.
|
2015-04-03 07:26:19 +00:00
|
|
|
* @callback {Function} callback Callback function called with `(err, instance)` arguments. Required.
|
2016-11-04 20:47:12 +00:00
|
|
|
* @param {Error} err Error object; see [Error object](http://loopback.io/doc/en/lb2/Error-object.html).
|
2015-04-03 07:26:19 +00:00
|
|
|
* @param {Object} instance Updated instance.
|
|
|
|
*/
|
|
|
|
|
2016-05-09 19:24:03 +00:00
|
|
|
PersistedModel.prototype.updateAttributes = PersistedModel.prototype.patchAttributes =
|
|
|
|
function updateAttributes(data, cb) {
|
2015-04-03 07:26:19 +00:00
|
|
|
throwNotAttached(this.modelName, 'updateAttributes');
|
|
|
|
};
|
2014-02-20 01:09:36 +00:00
|
|
|
|
2016-05-20 19:21:00 +00:00
|
|
|
/**
|
|
|
|
* Replace attributes for a model instance and persist it into the datasource.
|
|
|
|
* Performs validation before replacing.
|
|
|
|
*
|
|
|
|
* @param {Object} data Data to replace.
|
|
|
|
* @options {Object} [options] Options for replace
|
|
|
|
* @property {Boolean} validate Perform validation before saving. Default is true.
|
|
|
|
* @callback {Function} callback Callback function called with `(err, instance)` arguments.
|
2016-11-04 20:47:12 +00:00
|
|
|
* @param {Error} err Error object; see [Error object](http://loopback.io/doc/en/lb2/Error-object.html).
|
2016-05-20 19:21:00 +00:00
|
|
|
* @param {Object} instance Replaced instance.
|
|
|
|
*/
|
|
|
|
|
|
|
|
PersistedModel.prototype.replaceAttributes = function replaceAttributes(data, cb) {
|
|
|
|
throwNotAttached(this.modelName, 'replaceAttributes');
|
|
|
|
};
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Replace attributes for a model instance whose id is the first input
|
|
|
|
* argument and persist it into the datasource.
|
|
|
|
* Performs validation before replacing.
|
|
|
|
*
|
|
|
|
* @param {*} id The ID value of model instance to replace.
|
|
|
|
* @param {Object} data Data to replace.
|
|
|
|
* @options {Object} [options] Options for replace
|
|
|
|
* @property {Boolean} validate Perform validation before saving. Default is true.
|
|
|
|
* @callback {Function} callback Callback function called with `(err, instance)` arguments.
|
2016-11-04 20:47:12 +00:00
|
|
|
* @param {Error} err Error object; see [Error object](http://loopback.io/doc/en/lb2/Error-object.html).
|
2016-05-20 19:21:00 +00:00
|
|
|
* @param {Object} instance Replaced instance.
|
|
|
|
*/
|
|
|
|
|
|
|
|
PersistedModel.replaceById = function replaceById(id, data, cb) {
|
|
|
|
throwNotAttached(this.modelName, 'replaceById');
|
|
|
|
};
|
|
|
|
|
2015-04-03 07:26:19 +00:00
|
|
|
/**
|
|
|
|
* Reload object from persistence. Requires `id` member of `object` to be able to call `find`.
|
|
|
|
* @callback {Function} callback Callback function called with `(err, instance)` arguments. Required.
|
2016-11-04 20:47:12 +00:00
|
|
|
* @param {Error} err Error object; see [Error object](http://loopback.io/doc/en/lb2/Error-object.html).
|
2015-04-03 07:26:19 +00:00
|
|
|
* @param {Object} instance Model instance.
|
|
|
|
*/
|
2014-02-20 01:09:36 +00:00
|
|
|
|
2015-04-03 07:26:19 +00:00
|
|
|
PersistedModel.prototype.reload = function reload(callback) {
|
|
|
|
throwNotAttached(this.constructor.modelName, 'reload');
|
|
|
|
};
|
2014-02-20 01:09:36 +00:00
|
|
|
|
2015-04-03 07:26:19 +00:00
|
|
|
/**
|
|
|
|
* Set the correct `id` property for the `PersistedModel`. Uses the `setId` method if the model is attached to
|
|
|
|
* connector that defines it. Otherwise, uses the default lookup.
|
|
|
|
* Override this method to handle complex IDs.
|
|
|
|
*
|
|
|
|
* @param {*} val The `id` value. Will be converted to the type that the `id` property specifies.
|
|
|
|
*/
|
|
|
|
|
|
|
|
PersistedModel.prototype.setId = function(val) {
|
|
|
|
var ds = this.getDataSource();
|
|
|
|
this[this.getIdName()] = val;
|
|
|
|
};
|
2014-04-14 21:17:56 +00:00
|
|
|
|
2015-04-03 07:26:19 +00:00
|
|
|
/**
|
|
|
|
* Get the `id` value for the `PersistedModel`.
|
|
|
|
*
|
|
|
|
* @returns {*} The `id` value
|
|
|
|
*/
|
2014-04-14 21:17:56 +00:00
|
|
|
|
2015-04-03 07:26:19 +00:00
|
|
|
PersistedModel.prototype.getId = function() {
|
|
|
|
var data = this.toObject();
|
|
|
|
if (!data) return;
|
|
|
|
return data[this.getIdName()];
|
|
|
|
};
|
2014-04-14 21:17:56 +00:00
|
|
|
|
2015-04-03 07:26:19 +00:00
|
|
|
/**
|
|
|
|
* Get the `id` property name of the constructor.
|
|
|
|
*
|
|
|
|
* @returns {String} The `id` property name
|
|
|
|
*/
|
2014-05-03 01:12:24 +00:00
|
|
|
|
2015-04-03 07:26:19 +00:00
|
|
|
PersistedModel.prototype.getIdName = function() {
|
|
|
|
return this.constructor.getIdName();
|
|
|
|
};
|
2014-04-14 21:17:56 +00:00
|
|
|
|
2015-04-03 07:26:19 +00:00
|
|
|
/**
|
|
|
|
* Get the `id` property name of the constructor.
|
|
|
|
*
|
|
|
|
* @returns {String} The `id` property name
|
|
|
|
*/
|
2014-04-14 21:17:56 +00:00
|
|
|
|
2015-04-03 07:26:19 +00:00
|
|
|
PersistedModel.getIdName = function() {
|
|
|
|
var Model = this;
|
|
|
|
var ds = Model.getDataSource();
|
2014-04-14 21:17:56 +00:00
|
|
|
|
2015-04-03 07:26:19 +00:00
|
|
|
if (ds.idName) {
|
|
|
|
return ds.idName(Model.modelName);
|
|
|
|
} else {
|
|
|
|
return 'id';
|
|
|
|
}
|
|
|
|
};
|
2014-04-14 21:17:56 +00:00
|
|
|
|
2015-04-03 07:26:19 +00:00
|
|
|
PersistedModel.setupRemoting = function() {
|
|
|
|
var PersistedModel = this;
|
|
|
|
var typeName = PersistedModel.modelName;
|
|
|
|
var options = PersistedModel.settings;
|
2014-04-14 21:17:56 +00:00
|
|
|
|
2017-08-23 00:10:55 +00:00
|
|
|
// if there is atleast one updateOnly property, then we set
|
|
|
|
// createOnlyInstance flag in __create__ to indicate loopback-swagger
|
|
|
|
// code to create a separate model instance for create operation only
|
2017-08-23 14:21:11 +00:00
|
|
|
const updateOnlyProps = this.getUpdateOnlyProperties ?
|
|
|
|
this.getUpdateOnlyProperties() : false;
|
2017-08-23 00:10:55 +00:00
|
|
|
const hasUpdateOnlyProps = updateOnlyProps && updateOnlyProps.length > 0;
|
|
|
|
|
2016-05-09 19:24:03 +00:00
|
|
|
// This is just for LB 3.x
|
|
|
|
options.replaceOnPUT = options.replaceOnPUT !== false;
|
|
|
|
|
2015-04-03 07:26:19 +00:00
|
|
|
function setRemoting(scope, name, options) {
|
|
|
|
var fn = scope[name];
|
|
|
|
fn._delegate = true;
|
|
|
|
options.isStatic = scope === PersistedModel;
|
|
|
|
PersistedModel.remoteMethod(name, options);
|
|
|
|
}
|
2014-05-03 01:12:24 +00:00
|
|
|
|
2015-04-03 07:26:19 +00:00
|
|
|
setRemoting(PersistedModel, 'create', {
|
2016-08-15 09:06:05 +00:00
|
|
|
description: 'Create a new instance of the model and persist it into the data source.',
|
2015-04-03 07:26:19 +00:00
|
|
|
accessType: 'WRITE',
|
2016-09-20 08:54:41 +00:00
|
|
|
accepts: [
|
|
|
|
{
|
|
|
|
arg: 'data', type: 'object', model: typeName, allowArray: true,
|
2017-08-23 00:10:55 +00:00
|
|
|
createOnlyInstance: hasUpdateOnlyProps,
|
2016-09-20 08:54:41 +00:00
|
|
|
description: 'Model instance data',
|
|
|
|
http: {source: 'body'},
|
|
|
|
},
|
|
|
|
{arg: 'options', type: 'object', http: 'optionsFromRequest'},
|
|
|
|
],
|
2016-11-15 21:46:23 +00:00
|
|
|
returns: {arg: 'data', type: typeName, root: true},
|
|
|
|
http: {verb: 'post', path: '/'},
|
2015-04-03 07:26:19 +00:00
|
|
|
});
|
2014-05-03 01:12:24 +00:00
|
|
|
|
2016-05-09 19:24:03 +00:00
|
|
|
var upsertOptions = {
|
|
|
|
aliases: ['upsert', 'updateOrCreate'],
|
2016-08-15 09:06:05 +00:00
|
|
|
description: 'Patch an existing model instance or insert a new one ' +
|
|
|
|
'into the data source.',
|
2015-04-03 07:26:19 +00:00
|
|
|
accessType: 'WRITE',
|
2016-09-20 08:54:41 +00:00
|
|
|
accepts: [
|
|
|
|
{
|
|
|
|
arg: 'data', type: 'object', model: typeName, http: {source: 'body'},
|
|
|
|
description: 'Model instance data',
|
|
|
|
},
|
|
|
|
{arg: 'options', type: 'object', http: 'optionsFromRequest'},
|
|
|
|
],
|
2016-11-15 21:46:23 +00:00
|
|
|
returns: {arg: 'data', type: typeName, root: true},
|
|
|
|
http: [{verb: 'patch', path: '/'}],
|
2016-05-09 19:24:03 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
if (!options.replaceOnPUT) {
|
2016-11-15 21:46:23 +00:00
|
|
|
upsertOptions.http.unshift({verb: 'put', path: '/'});
|
2016-05-09 19:24:03 +00:00
|
|
|
}
|
|
|
|
setRemoting(PersistedModel, 'patchOrCreate', upsertOptions);
|
|
|
|
|
|
|
|
var replaceOrCreateOptions = {
|
|
|
|
description: 'Replace an existing model instance or insert a new one into the data source.',
|
|
|
|
accessType: 'WRITE',
|
2016-09-20 08:54:41 +00:00
|
|
|
accepts: [
|
|
|
|
{
|
|
|
|
arg: 'data', type: 'object', model: typeName,
|
|
|
|
http: {source: 'body'},
|
|
|
|
description: 'Model instance data',
|
|
|
|
},
|
|
|
|
{arg: 'options', type: 'object', http: 'optionsFromRequest'},
|
|
|
|
],
|
2016-11-15 21:46:23 +00:00
|
|
|
returns: {arg: 'data', type: typeName, root: true},
|
|
|
|
http: [{verb: 'post', path: '/replaceOrCreate'}],
|
2016-05-09 19:24:03 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
if (options.replaceOnPUT) {
|
2016-11-15 21:46:23 +00:00
|
|
|
replaceOrCreateOptions.http.push({verb: 'put', path: '/'});
|
2016-05-09 19:24:03 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
setRemoting(PersistedModel, 'replaceOrCreate', replaceOrCreateOptions);
|
2014-05-14 16:20:04 +00:00
|
|
|
|
2016-09-02 12:40:47 +00:00
|
|
|
setRemoting(PersistedModel, 'upsertWithWhere', {
|
|
|
|
aliases: ['patchOrCreateWithWhere'],
|
|
|
|
description: 'Update an existing model instance or insert a new one into ' +
|
|
|
|
'the data source based on the where criteria.',
|
|
|
|
accessType: 'WRITE',
|
|
|
|
accepts: [
|
2016-11-15 21:46:23 +00:00
|
|
|
{arg: 'where', type: 'object', http: {source: 'query'},
|
|
|
|
description: 'Criteria to match model instances'},
|
|
|
|
{arg: 'data', type: 'object', model: typeName, http: {source: 'body'},
|
|
|
|
description: 'An object of model property name/value pairs'},
|
2016-09-20 08:54:41 +00:00
|
|
|
{arg: 'options', type: 'object', http: 'optionsFromRequest'},
|
2016-09-02 12:40:47 +00:00
|
|
|
],
|
2016-11-15 21:46:23 +00:00
|
|
|
returns: {arg: 'data', type: typeName, root: true},
|
|
|
|
http: {verb: 'post', path: '/upsertWithWhere'},
|
2016-09-02 12:40:47 +00:00
|
|
|
});
|
|
|
|
|
2015-04-03 07:26:19 +00:00
|
|
|
setRemoting(PersistedModel, 'exists', {
|
2016-08-15 09:06:05 +00:00
|
|
|
description: 'Check whether a model instance exists in the data source.',
|
2014-12-12 16:50:17 +00:00
|
|
|
accessType: 'READ',
|
2016-09-20 08:54:41 +00:00
|
|
|
accepts: [
|
|
|
|
{arg: 'id', type: 'any', description: 'Model id', required: true},
|
|
|
|
{arg: 'options', type: 'object', http: 'optionsFromRequest'},
|
|
|
|
],
|
2016-11-15 21:46:23 +00:00
|
|
|
returns: {arg: 'exists', type: 'boolean'},
|
2015-04-03 07:26:19 +00:00
|
|
|
http: [
|
2016-11-15 21:46:23 +00:00
|
|
|
{verb: 'get', path: '/:id/exists'},
|
|
|
|
{verb: 'head', path: '/:id'},
|
2014-10-16 22:54:40 +00:00
|
|
|
],
|
2015-04-03 07:26:19 +00:00
|
|
|
rest: {
|
|
|
|
// After hook to map exists to 200/404 for HEAD
|
|
|
|
after: function(ctx, cb) {
|
|
|
|
if (ctx.req.method === 'GET') {
|
|
|
|
// For GET, return {exists: true|false} as is
|
|
|
|
return cb();
|
|
|
|
}
|
|
|
|
if (!ctx.result.exists) {
|
|
|
|
var modelName = ctx.method.sharedClass.name;
|
|
|
|
var id = ctx.getArgByName('id');
|
|
|
|
var msg = 'Unknown "' + modelName + '" id "' + id + '".';
|
|
|
|
var error = new Error(msg);
|
|
|
|
error.statusCode = error.status = 404;
|
|
|
|
error.code = 'MODEL_NOT_FOUND';
|
|
|
|
cb(error);
|
|
|
|
} else {
|
|
|
|
cb();
|
|
|
|
}
|
2016-04-01 09:14:26 +00:00
|
|
|
},
|
|
|
|
},
|
2014-05-06 20:31:23 +00:00
|
|
|
});
|
|
|
|
|
2015-04-03 07:26:19 +00:00
|
|
|
setRemoting(PersistedModel, 'findById', {
|
2016-08-15 09:06:05 +00:00
|
|
|
description: 'Find a model instance by {{id}} from the data source.',
|
2014-12-12 16:50:17 +00:00
|
|
|
accessType: 'READ',
|
2015-04-16 22:02:41 +00:00
|
|
|
accepts: [
|
2016-11-15 21:46:23 +00:00
|
|
|
{arg: 'id', type: 'any', description: 'Model id', required: true,
|
|
|
|
http: {source: 'path'}},
|
|
|
|
{arg: 'filter', type: 'object',
|
2017-02-20 16:30:01 +00:00
|
|
|
description:
|
|
|
|
'Filter defining fields and include - must be a JSON-encoded string (' +
|
|
|
|
'{"something":"value"})'},
|
2016-09-20 08:54:41 +00:00
|
|
|
{arg: 'options', type: 'object', http: 'optionsFromRequest'},
|
2015-04-16 22:02:41 +00:00
|
|
|
],
|
2016-11-15 21:46:23 +00:00
|
|
|
returns: {arg: 'data', type: typeName, root: true},
|
|
|
|
http: {verb: 'get', path: '/:id'},
|
|
|
|
rest: {after: convertNullToNotFoundError},
|
2014-05-06 20:31:23 +00:00
|
|
|
});
|
2014-10-16 22:54:40 +00:00
|
|
|
|
2016-05-09 19:24:03 +00:00
|
|
|
var replaceByIdOptions = {
|
|
|
|
description: 'Replace attributes for a model instance and persist it into the data source.',
|
|
|
|
accessType: 'WRITE',
|
|
|
|
accepts: [
|
2016-11-15 21:46:23 +00:00
|
|
|
{arg: 'id', type: 'any', description: 'Model id', required: true,
|
|
|
|
http: {source: 'path'}},
|
2016-12-06 14:40:42 +00:00
|
|
|
{arg: 'data', type: 'object', model: typeName, http: {source: 'body'}, description:
|
2016-09-20 08:54:41 +00:00
|
|
|
'Model instance data'},
|
|
|
|
{arg: 'options', type: 'object', http: 'optionsFromRequest'},
|
2016-05-09 19:24:03 +00:00
|
|
|
],
|
2016-11-15 21:46:23 +00:00
|
|
|
returns: {arg: 'data', type: typeName, root: true},
|
|
|
|
http: [{verb: 'post', path: '/:id/replace'}],
|
2016-05-09 19:24:03 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
if (options.replaceOnPUT) {
|
2016-11-15 21:46:23 +00:00
|
|
|
replaceByIdOptions.http.push({verb: 'put', path: '/:id'});
|
2016-05-09 19:24:03 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
setRemoting(PersistedModel, 'replaceById', replaceByIdOptions);
|
|
|
|
|
2015-04-03 07:26:19 +00:00
|
|
|
setRemoting(PersistedModel, 'find', {
|
2016-08-15 09:06:05 +00:00
|
|
|
description: 'Find all instances of the model matched by filter from the data source.',
|
2015-04-03 07:26:19 +00:00
|
|
|
accessType: 'READ',
|
2016-09-20 08:54:41 +00:00
|
|
|
accepts: [
|
|
|
|
{arg: 'filter', type: 'object', description:
|
2017-02-20 16:30:01 +00:00
|
|
|
'Filter defining fields, where, include, order, offset, and limit - must be a ' +
|
|
|
|
'JSON-encoded string ({"something":"value"})'},
|
2016-09-20 08:54:41 +00:00
|
|
|
{arg: 'options', type: 'object', http: 'optionsFromRequest'},
|
|
|
|
],
|
2016-11-15 21:46:23 +00:00
|
|
|
returns: {arg: 'data', type: [typeName], root: true},
|
|
|
|
http: {verb: 'get', path: '/'},
|
2014-05-06 20:31:23 +00:00
|
|
|
});
|
|
|
|
|
2015-04-03 07:26:19 +00:00
|
|
|
setRemoting(PersistedModel, 'findOne', {
|
2016-08-15 09:06:05 +00:00
|
|
|
description: 'Find first instance of the model matched by filter from the data source.',
|
2014-12-12 16:50:17 +00:00
|
|
|
accessType: 'READ',
|
2016-09-20 08:54:41 +00:00
|
|
|
accepts: [
|
|
|
|
{arg: 'filter', type: 'object', description:
|
2017-02-20 16:30:01 +00:00
|
|
|
'Filter defining fields, where, include, order, offset, and limit - must be a ' +
|
|
|
|
'JSON-encoded string ({"something":"value"})'},
|
2016-09-20 08:54:41 +00:00
|
|
|
{arg: 'options', type: 'object', http: 'optionsFromRequest'},
|
|
|
|
],
|
2016-11-15 21:46:23 +00:00
|
|
|
returns: {arg: 'data', type: typeName, root: true},
|
|
|
|
http: {verb: 'get', path: '/findOne'},
|
|
|
|
rest: {after: convertNullToNotFoundError},
|
2014-05-06 20:31:23 +00:00
|
|
|
});
|
|
|
|
|
2015-04-03 07:26:19 +00:00
|
|
|
setRemoting(PersistedModel, 'destroyAll', {
|
2016-08-15 09:06:05 +00:00
|
|
|
description: 'Delete all matching records.',
|
2014-12-12 16:50:17 +00:00
|
|
|
accessType: 'WRITE',
|
2016-09-20 08:54:41 +00:00
|
|
|
accepts: [
|
|
|
|
{arg: 'where', type: 'object', description: 'filter.where object'},
|
|
|
|
{arg: 'options', type: 'object', http: 'optionsFromRequest'},
|
|
|
|
],
|
2015-09-19 02:13:30 +00:00
|
|
|
returns: {
|
|
|
|
arg: 'count',
|
|
|
|
type: 'object',
|
|
|
|
description: 'The number of instances deleted',
|
2016-04-01 09:14:26 +00:00
|
|
|
root: true,
|
2015-09-19 02:13:30 +00:00
|
|
|
},
|
2016-11-15 21:46:23 +00:00
|
|
|
http: {verb: 'del', path: '/'},
|
2016-04-01 09:14:26 +00:00
|
|
|
shared: false,
|
2014-05-10 00:19:32 +00:00
|
|
|
});
|
|
|
|
|
2015-04-03 07:26:19 +00:00
|
|
|
setRemoting(PersistedModel, 'updateAll', {
|
|
|
|
aliases: ['update'],
|
2016-08-15 09:06:05 +00:00
|
|
|
description: 'Update instances of the model matched by {{where}} from the data source.',
|
2014-12-12 16:50:17 +00:00
|
|
|
accessType: 'WRITE',
|
2015-04-03 07:26:19 +00:00
|
|
|
accepts: [
|
2016-11-15 21:46:23 +00:00
|
|
|
{arg: 'where', type: 'object', http: {source: 'query'},
|
|
|
|
description: 'Criteria to match model instances'},
|
|
|
|
{arg: 'data', type: 'object', model: typeName, http: {source: 'body'},
|
|
|
|
description: 'An object of model property name/value pairs'},
|
2016-09-20 08:54:41 +00:00
|
|
|
{arg: 'options', type: 'object', http: 'optionsFromRequest'},
|
2015-04-03 07:26:19 +00:00
|
|
|
],
|
2015-09-19 02:13:30 +00:00
|
|
|
returns: {
|
2016-10-11 14:31:57 +00:00
|
|
|
arg: 'info',
|
|
|
|
description: 'Information related to the outcome of the operation',
|
|
|
|
type: {
|
|
|
|
count: {
|
|
|
|
type: 'number',
|
|
|
|
description: 'The number of instances updated',
|
|
|
|
},
|
|
|
|
},
|
2016-04-01 09:14:26 +00:00
|
|
|
root: true,
|
2015-09-19 02:13:30 +00:00
|
|
|
},
|
2016-11-15 21:46:23 +00:00
|
|
|
http: {verb: 'post', path: '/update'},
|
2014-05-06 20:31:23 +00:00
|
|
|
});
|
2014-05-10 00:19:32 +00:00
|
|
|
|
2015-04-03 07:26:19 +00:00
|
|
|
setRemoting(PersistedModel, 'deleteById', {
|
|
|
|
aliases: ['destroyById', 'removeById'],
|
2016-08-15 09:06:05 +00:00
|
|
|
description: 'Delete a model instance by {{id}} from the data source.',
|
2014-12-12 16:50:17 +00:00
|
|
|
accessType: 'WRITE',
|
2016-09-20 08:54:41 +00:00
|
|
|
accepts: [
|
|
|
|
{arg: 'id', type: 'any', description: 'Model id', required: true,
|
|
|
|
http: {source: 'path'}},
|
|
|
|
{arg: 'options', type: 'object', http: 'optionsFromRequest'},
|
|
|
|
],
|
2016-11-15 21:46:23 +00:00
|
|
|
http: {verb: 'del', path: '/:id'},
|
|
|
|
returns: {arg: 'count', type: 'object', root: true},
|
2014-05-10 00:19:32 +00:00
|
|
|
});
|
|
|
|
|
2015-04-03 07:26:19 +00:00
|
|
|
setRemoting(PersistedModel, 'count', {
|
2016-08-15 09:06:05 +00:00
|
|
|
description: 'Count instances of the model matched by where from the data source.',
|
2015-04-03 07:26:19 +00:00
|
|
|
accessType: 'READ',
|
2016-09-20 08:54:41 +00:00
|
|
|
accepts: [
|
|
|
|
{arg: 'where', type: 'object', description: 'Criteria to match model instances'},
|
|
|
|
{arg: 'options', type: 'object', http: 'optionsFromRequest'},
|
|
|
|
],
|
2016-11-15 21:46:23 +00:00
|
|
|
returns: {arg: 'count', type: 'number'},
|
|
|
|
http: {verb: 'get', path: '/count'},
|
2014-05-10 00:19:32 +00:00
|
|
|
});
|
2014-05-06 20:31:23 +00:00
|
|
|
|
2016-05-09 19:24:03 +00:00
|
|
|
var updateAttributesOptions = {
|
|
|
|
aliases: ['updateAttributes'],
|
2016-08-15 09:06:05 +00:00
|
|
|
description: 'Patch attributes for a model instance and persist it into ' +
|
|
|
|
'the data source.',
|
2015-04-03 07:26:19 +00:00
|
|
|
accessType: 'WRITE',
|
2016-09-20 08:54:41 +00:00
|
|
|
accepts: [
|
|
|
|
{
|
|
|
|
arg: 'data', type: 'object', model: typeName,
|
|
|
|
http: {source: 'body'},
|
|
|
|
description: 'An object of model property name/value pairs',
|
|
|
|
},
|
|
|
|
{arg: 'options', type: 'object', http: 'optionsFromRequest'},
|
|
|
|
],
|
2016-11-15 21:46:23 +00:00
|
|
|
returns: {arg: 'data', type: typeName, root: true},
|
|
|
|
http: [{verb: 'patch', path: '/'}],
|
2016-05-09 19:24:03 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
setRemoting(PersistedModel.prototype, 'patchAttributes', updateAttributesOptions);
|
|
|
|
|
|
|
|
if (!options.replaceOnPUT) {
|
2016-11-15 21:46:23 +00:00
|
|
|
updateAttributesOptions.http.unshift({verb: 'put', path: '/'});
|
2016-05-09 19:24:03 +00:00
|
|
|
}
|
2014-05-06 20:31:23 +00:00
|
|
|
|
2015-04-03 14:41:32 +00:00
|
|
|
if (options.trackChanges || options.enableRemoteReplication) {
|
2015-04-03 07:26:19 +00:00
|
|
|
setRemoting(PersistedModel, 'diff', {
|
2016-08-15 09:06:05 +00:00
|
|
|
description: 'Get a set of deltas and conflicts since the given checkpoint.',
|
2015-04-03 07:26:19 +00:00
|
|
|
accessType: 'READ',
|
|
|
|
accepts: [
|
2016-11-15 21:46:23 +00:00
|
|
|
{arg: 'since', type: 'number', description: 'Find deltas since this checkpoint'},
|
|
|
|
{arg: 'remoteChanges', type: 'array', description: 'an array of change objects',
|
2016-12-06 14:40:42 +00:00
|
|
|
http: {source: 'body'}},
|
2015-04-03 07:26:19 +00:00
|
|
|
],
|
2016-11-15 21:46:23 +00:00
|
|
|
returns: {arg: 'result', type: 'object', root: true},
|
|
|
|
http: {verb: 'post', path: '/diff'},
|
2015-04-03 07:26:19 +00:00
|
|
|
});
|
2014-05-06 20:31:23 +00:00
|
|
|
|
2015-04-03 07:26:19 +00:00
|
|
|
setRemoting(PersistedModel, 'changes', {
|
2016-08-15 09:06:05 +00:00
|
|
|
description: 'Get the changes to a model since a given checkpoint.' +
|
|
|
|
'Provide a filter object to reduce the number of results returned.',
|
2015-04-03 07:26:19 +00:00
|
|
|
accessType: 'READ',
|
|
|
|
accepts: [
|
2016-11-15 21:46:23 +00:00
|
|
|
{arg: 'since', type: 'number', description:
|
|
|
|
'Only return changes since this checkpoint'},
|
|
|
|
{arg: 'filter', type: 'object', description:
|
|
|
|
'Only include changes that match this filter'},
|
2015-04-03 07:26:19 +00:00
|
|
|
],
|
2016-11-15 21:46:23 +00:00
|
|
|
returns: {arg: 'changes', type: 'array', root: true},
|
|
|
|
http: {verb: 'get', path: '/changes'},
|
2015-04-03 07:26:19 +00:00
|
|
|
});
|
2014-05-06 20:31:23 +00:00
|
|
|
|
2015-04-03 07:26:19 +00:00
|
|
|
setRemoting(PersistedModel, 'checkpoint', {
|
2016-08-15 09:06:05 +00:00
|
|
|
description: 'Create a checkpoint.',
|
2015-04-03 14:41:32 +00:00
|
|
|
// The replication algorithm needs to create a source checkpoint,
|
|
|
|
// even though it is otherwise not making any source changes.
|
|
|
|
// We need to allow this method for users that don't have full
|
|
|
|
// WRITE permissions.
|
|
|
|
accessType: 'REPLICATE',
|
2016-11-15 21:46:23 +00:00
|
|
|
returns: {arg: 'checkpoint', type: 'object', root: true},
|
|
|
|
http: {verb: 'post', path: '/checkpoint'},
|
2015-04-03 07:26:19 +00:00
|
|
|
});
|
2014-05-10 00:19:32 +00:00
|
|
|
|
2015-04-03 07:26:19 +00:00
|
|
|
setRemoting(PersistedModel, 'currentCheckpoint', {
|
2016-08-15 09:06:05 +00:00
|
|
|
description: 'Get the current checkpoint.',
|
2015-04-03 07:26:19 +00:00
|
|
|
accessType: 'READ',
|
2016-11-15 21:46:23 +00:00
|
|
|
returns: {arg: 'checkpoint', type: 'object', root: true},
|
|
|
|
http: {verb: 'get', path: '/checkpoint'},
|
2014-05-06 20:31:23 +00:00
|
|
|
});
|
|
|
|
|
2015-04-03 07:26:19 +00:00
|
|
|
setRemoting(PersistedModel, 'createUpdates', {
|
2016-08-15 09:06:05 +00:00
|
|
|
description: 'Create an update list from a delta list.',
|
2015-04-03 14:41:32 +00:00
|
|
|
// This operation is read-only, it does not change any local data.
|
|
|
|
// It is called by the replication algorithm to compile a list
|
|
|
|
// of changes to apply on the target.
|
|
|
|
accessType: 'READ',
|
2016-11-15 21:46:23 +00:00
|
|
|
accepts: {arg: 'deltas', type: 'array', http: {source: 'body'}},
|
|
|
|
returns: {arg: 'updates', type: 'array', root: true},
|
|
|
|
http: {verb: 'post', path: '/create-updates'},
|
2015-04-03 07:26:19 +00:00
|
|
|
});
|
2014-05-06 20:31:23 +00:00
|
|
|
|
2015-04-03 07:26:19 +00:00
|
|
|
setRemoting(PersistedModel, 'bulkUpdate', {
|
2016-08-15 09:06:05 +00:00
|
|
|
description: 'Run multiple updates at once. Note: this is not atomic.',
|
2015-04-03 07:26:19 +00:00
|
|
|
accessType: 'WRITE',
|
2016-11-15 21:46:23 +00:00
|
|
|
accepts: {arg: 'updates', type: 'array'},
|
|
|
|
http: {verb: 'post', path: '/bulk-update'},
|
2015-04-03 07:26:19 +00:00
|
|
|
});
|
2015-04-09 10:44:29 +00:00
|
|
|
|
|
|
|
setRemoting(PersistedModel, 'findLastChange', {
|
2016-08-15 09:06:05 +00:00
|
|
|
description: 'Get the most recent change record for this instance.',
|
2015-04-09 10:44:29 +00:00
|
|
|
accessType: 'READ',
|
|
|
|
accepts: {
|
2016-11-15 21:46:23 +00:00
|
|
|
arg: 'id', type: 'any', required: true, http: {source: 'path'},
|
2016-04-01 09:14:26 +00:00
|
|
|
description: 'Model id',
|
2015-04-09 10:44:29 +00:00
|
|
|
},
|
2016-11-15 21:46:23 +00:00
|
|
|
returns: {arg: 'result', type: this.Change.modelName, root: true},
|
|
|
|
http: {verb: 'get', path: '/:id/changes/last'},
|
2015-04-09 10:44:29 +00:00
|
|
|
});
|
|
|
|
|
|
|
|
setRemoting(PersistedModel, 'updateLastChange', {
|
2016-08-15 09:06:05 +00:00
|
|
|
description:
|
|
|
|
'Update the properties of the most recent change record ' +
|
|
|
|
'kept for this instance.',
|
2015-04-09 10:44:29 +00:00
|
|
|
accessType: 'WRITE',
|
|
|
|
accepts: [
|
|
|
|
{
|
2016-11-15 21:46:23 +00:00
|
|
|
arg: 'id', type: 'any', required: true, http: {source: 'path'},
|
2016-04-01 09:14:26 +00:00
|
|
|
description: 'Model id',
|
2015-04-09 10:44:29 +00:00
|
|
|
},
|
|
|
|
{
|
2016-11-15 21:46:23 +00:00
|
|
|
arg: 'data', type: 'object', model: typeName, http: {source: 'body'},
|
2016-08-15 09:06:05 +00:00
|
|
|
description: 'An object of Change property name/value pairs',
|
2015-04-09 10:44:29 +00:00
|
|
|
},
|
|
|
|
],
|
2016-11-15 21:46:23 +00:00
|
|
|
returns: {arg: 'result', type: this.Change.modelName, root: true},
|
|
|
|
http: {verb: 'put', path: '/:id/changes/last'},
|
2015-04-09 10:44:29 +00:00
|
|
|
});
|
2015-04-03 14:41:32 +00:00
|
|
|
}
|
2014-05-06 20:31:23 +00:00
|
|
|
|
2015-07-09 20:30:50 +00:00
|
|
|
setRemoting(PersistedModel, 'createChangeStream', {
|
2016-08-15 09:06:05 +00:00
|
|
|
description: 'Create a change stream.',
|
2015-07-09 20:30:50 +00:00
|
|
|
accessType: 'READ',
|
|
|
|
http: [
|
2016-11-15 21:46:23 +00:00
|
|
|
{verb: 'post', path: '/change-stream'},
|
|
|
|
{verb: 'get', path: '/change-stream'},
|
2015-07-09 20:30:50 +00:00
|
|
|
],
|
|
|
|
accepts: {
|
|
|
|
arg: 'options',
|
2016-04-01 09:14:26 +00:00
|
|
|
type: 'object',
|
2015-07-09 20:30:50 +00:00
|
|
|
},
|
|
|
|
returns: {
|
|
|
|
arg: 'changes',
|
|
|
|
type: 'ReadableStream',
|
2016-04-01 09:14:26 +00:00
|
|
|
json: true,
|
|
|
|
},
|
2015-07-09 20:30:50 +00:00
|
|
|
});
|
2015-04-03 07:26:19 +00:00
|
|
|
};
|
2014-05-06 20:31:23 +00:00
|
|
|
|
2015-04-03 07:26:19 +00:00
|
|
|
/**
|
|
|
|
* Get a set of deltas and conflicts since the given checkpoint.
|
|
|
|
*
|
|
|
|
* See [Change.diff()](#change-diff) for details.
|
|
|
|
*
|
|
|
|
* @param {Number} since Find deltas since this checkpoint.
|
|
|
|
* @param {Array} remoteChanges An array of change objects.
|
|
|
|
* @callback {Function} callback Callback function called with `(err, result)` arguments. Required.
|
2016-11-04 20:47:12 +00:00
|
|
|
* @param {Error} err Error object; see [Error object](http://loopback.io/doc/en/lb2/Error-object.html).
|
2015-04-03 07:26:19 +00:00
|
|
|
* @param {Object} result Object with `deltas` and `conflicts` properties; see [Change.diff()](#change-diff) for details.
|
|
|
|
*/
|
|
|
|
|
|
|
|
PersistedModel.diff = function(since, remoteChanges, callback) {
|
|
|
|
var Change = this.getChangeModel();
|
|
|
|
Change.diff(this.modelName, since, remoteChanges, callback);
|
|
|
|
};
|
2014-05-06 20:31:23 +00:00
|
|
|
|
2015-04-03 07:26:19 +00:00
|
|
|
/**
|
|
|
|
* Get the changes to a model since the specified checkpoint. Provide a filter object
|
|
|
|
* to reduce the number of results returned.
|
|
|
|
* @param {Number} since Return only changes since this checkpoint.
|
|
|
|
* @param {Object} filter Include only changes that match this filter, the same as for [#persistedmodel-find](find()).
|
|
|
|
* @callback {Function} callback Callback function called with `(err, changes)` arguments. Required.
|
2016-11-04 20:47:12 +00:00
|
|
|
* @param {Error} err Error object; see [Error object](http://loopback.io/doc/en/lb2/Error-object.html).
|
2015-04-03 07:26:19 +00:00
|
|
|
* @param {Array} changes An array of [Change](#change) objects.
|
|
|
|
*/
|
|
|
|
|
|
|
|
PersistedModel.changes = function(since, filter, callback) {
|
|
|
|
if (typeof since === 'function') {
|
|
|
|
filter = {};
|
|
|
|
callback = since;
|
|
|
|
since = -1;
|
|
|
|
}
|
|
|
|
if (typeof filter === 'function') {
|
|
|
|
callback = filter;
|
|
|
|
since = -1;
|
|
|
|
filter = {};
|
|
|
|
}
|
2014-05-06 20:31:23 +00:00
|
|
|
|
2015-04-03 07:26:19 +00:00
|
|
|
var idName = this.dataSource.idName(this.modelName);
|
|
|
|
var Change = this.getChangeModel();
|
|
|
|
var model = this;
|
2016-11-21 08:13:16 +00:00
|
|
|
const changeFilter = this.createChangeFilter(since, filter);
|
2014-05-06 20:31:23 +00:00
|
|
|
|
2015-04-03 07:26:19 +00:00
|
|
|
filter = filter || {};
|
|
|
|
filter.fields = {};
|
|
|
|
filter.where = filter.where || {};
|
|
|
|
filter.fields[idName] = true;
|
2014-05-06 20:31:23 +00:00
|
|
|
|
2015-04-03 07:26:19 +00:00
|
|
|
// TODO(ritch) this whole thing could be optimized a bit more
|
2016-11-21 08:13:16 +00:00
|
|
|
Change.find(changeFilter, function(err, changes) {
|
2015-04-03 07:26:19 +00:00
|
|
|
if (err) return callback(err);
|
|
|
|
if (!Array.isArray(changes) || changes.length === 0) return callback(null, []);
|
|
|
|
var ids = changes.map(function(change) {
|
|
|
|
return change.getModelId();
|
|
|
|
});
|
2016-11-15 21:46:23 +00:00
|
|
|
filter.where[idName] = {inq: ids};
|
2015-04-03 07:26:19 +00:00
|
|
|
model.find(filter, function(err, models) {
|
|
|
|
if (err) return callback(err);
|
|
|
|
var modelIds = models.map(function(m) {
|
|
|
|
return m[idName].toString();
|
|
|
|
});
|
|
|
|
callback(null, changes.filter(function(ch) {
|
|
|
|
if (ch.type() === Change.DELETE) return true;
|
|
|
|
return modelIds.indexOf(ch.modelId) > -1;
|
|
|
|
}));
|
|
|
|
});
|
|
|
|
});
|
|
|
|
};
|
2015-03-03 10:23:13 +00:00
|
|
|
|
2015-04-03 07:26:19 +00:00
|
|
|
/**
|
|
|
|
* Create a checkpoint.
|
|
|
|
*
|
|
|
|
* @param {Function} callback
|
|
|
|
*/
|
2014-05-06 20:31:23 +00:00
|
|
|
|
2015-04-03 07:26:19 +00:00
|
|
|
PersistedModel.checkpoint = function(cb) {
|
|
|
|
var Checkpoint = this.getChangeModel().getCheckpointModel();
|
2015-12-17 17:02:35 +00:00
|
|
|
Checkpoint.bumpLastSeq(cb);
|
2014-10-16 22:54:40 +00:00
|
|
|
};
|
2014-05-06 20:31:23 +00:00
|
|
|
|
2015-04-03 07:26:19 +00:00
|
|
|
/**
|
|
|
|
* Get the current checkpoint ID.
|
|
|
|
*
|
|
|
|
* @callback {Function} callback Callback function called with `(err, currentCheckpointId)` arguments. Required.
|
2016-11-04 20:47:12 +00:00
|
|
|
* @param {Error} err Error object; see [Error object](http://loopback.io/doc/en/lb2/Error-object.html).
|
2015-04-03 07:26:19 +00:00
|
|
|
* @param {Number} currentCheckpointId Current checkpoint ID.
|
|
|
|
*/
|
|
|
|
|
|
|
|
PersistedModel.currentCheckpoint = function(cb) {
|
|
|
|
var Checkpoint = this.getChangeModel().getCheckpointModel();
|
|
|
|
Checkpoint.current(cb);
|
|
|
|
};
|
2015-03-04 14:00:53 +00:00
|
|
|
|
2015-04-03 07:26:19 +00:00
|
|
|
/**
|
|
|
|
* Replicate changes since the given checkpoint to the given target model.
|
|
|
|
*
|
|
|
|
* @param {Number} [since] Since this checkpoint
|
|
|
|
* @param {Model} targetModel Target this model class
|
2016-11-15 02:02:23 +00:00
|
|
|
* @param {Object} [options] An optional options object to pass to underlying data-access calls.
|
2015-04-03 07:26:19 +00:00
|
|
|
* @param {Object} [options.filter] Replicate models that match this filter
|
|
|
|
* @callback {Function} [callback] Callback function called with `(err, conflicts)` arguments.
|
2016-11-04 20:47:12 +00:00
|
|
|
* @param {Error} err Error object; see [Error object](http://loopback.io/doc/en/lb2/Error-object.html).
|
2015-04-03 07:26:19 +00:00
|
|
|
* @param {Conflict[]} conflicts A list of changes that could not be replicated due to conflicts.
|
2016-02-04 20:31:39 +00:00
|
|
|
* @param {Object} checkpoints The new checkpoints to use as the "since"
|
2015-04-03 07:26:19 +00:00
|
|
|
* argument for the next replication.
|
2016-02-04 20:31:39 +00:00
|
|
|
*
|
|
|
|
* @promise
|
2015-04-03 07:26:19 +00:00
|
|
|
*/
|
|
|
|
|
|
|
|
PersistedModel.replicate = function(since, targetModel, options, callback) {
|
|
|
|
var lastArg = arguments[arguments.length - 1];
|
|
|
|
|
|
|
|
if (typeof lastArg === 'function' && arguments.length > 1) {
|
|
|
|
callback = lastArg;
|
2015-03-05 12:13:21 +00:00
|
|
|
}
|
|
|
|
|
2015-04-03 07:26:19 +00:00
|
|
|
if (typeof since === 'function' && since.modelName) {
|
|
|
|
targetModel = since;
|
|
|
|
since = -1;
|
|
|
|
}
|
2015-03-05 12:13:21 +00:00
|
|
|
|
2015-04-03 07:26:19 +00:00
|
|
|
if (typeof since !== 'object') {
|
2016-11-15 21:46:23 +00:00
|
|
|
since = {source: since, target: since};
|
2015-04-03 07:26:19 +00:00
|
|
|
}
|
2014-05-06 20:31:23 +00:00
|
|
|
|
2016-11-15 02:02:23 +00:00
|
|
|
if (typeof options === 'function') {
|
|
|
|
options = {};
|
|
|
|
}
|
|
|
|
|
2015-04-03 07:26:19 +00:00
|
|
|
options = options || {};
|
2014-05-06 20:31:23 +00:00
|
|
|
|
2015-04-03 07:26:19 +00:00
|
|
|
var sourceModel = this;
|
2015-07-20 12:00:05 +00:00
|
|
|
callback = callback || utils.createPromiseCallback();
|
2015-03-04 14:00:53 +00:00
|
|
|
|
2015-04-03 07:26:19 +00:00
|
|
|
debug('replicating %s since %s to %s since %s',
|
|
|
|
sourceModel.modelName,
|
|
|
|
since.source,
|
|
|
|
targetModel.modelName,
|
|
|
|
since.target);
|
|
|
|
if (options.filter) {
|
|
|
|
debug('\twith filter %j', options.filter);
|
2015-03-04 14:00:53 +00:00
|
|
|
}
|
2014-05-06 20:31:23 +00:00
|
|
|
|
2015-04-03 07:26:19 +00:00
|
|
|
// In order to avoid a race condition between the replication and
|
|
|
|
// other clients modifying the data, we must create the new target
|
|
|
|
// checkpoint as the first step of the replication process.
|
|
|
|
// As a side-effect of that, the replicated changes are associated
|
|
|
|
// with the new target checkpoint. This is actually desired behaviour,
|
|
|
|
// because that way clients replicating *from* the target model
|
|
|
|
// since the new checkpoint will pick these changes up.
|
|
|
|
// However, it increases the likelihood of (false) conflicts being detected.
|
|
|
|
// In order to prevent that, we run the replication multiple times,
|
|
|
|
// until no changes were replicated, but at most MAX_ATTEMPTS times
|
|
|
|
// to prevent starvation. In most cases, the second run will find no changes
|
|
|
|
// to replicate and we are done.
|
|
|
|
var MAX_ATTEMPTS = 3;
|
|
|
|
|
|
|
|
run(1, since);
|
2015-07-20 12:00:05 +00:00
|
|
|
return callback.promise;
|
2015-04-03 07:26:19 +00:00
|
|
|
|
|
|
|
function run(attempt, since) {
|
|
|
|
debug('\titeration #%s', attempt);
|
|
|
|
tryReplicate(sourceModel, targetModel, since, options, next);
|
|
|
|
|
|
|
|
function next(err, conflicts, cps, updates) {
|
|
|
|
var finished = err || conflicts.length ||
|
|
|
|
!updates || updates.length === 0 ||
|
|
|
|
attempt >= MAX_ATTEMPTS;
|
|
|
|
|
|
|
|
if (finished)
|
|
|
|
return callback(err, conflicts, cps);
|
|
|
|
run(attempt + 1, cps);
|
2015-03-04 14:00:53 +00:00
|
|
|
}
|
|
|
|
}
|
2015-04-03 07:26:19 +00:00
|
|
|
};
|
2014-05-06 20:31:23 +00:00
|
|
|
|
2015-04-03 07:26:19 +00:00
|
|
|
function tryReplicate(sourceModel, targetModel, since, options, callback) {
|
|
|
|
var Change = sourceModel.getChangeModel();
|
|
|
|
var TargetChange = targetModel.getChangeModel();
|
|
|
|
var changeTrackingEnabled = Change && TargetChange;
|
2016-11-21 08:48:43 +00:00
|
|
|
var replicationChunkSize = REPLICATION_CHUNK_SIZE;
|
|
|
|
|
|
|
|
if (sourceModel.settings && sourceModel.settings.replicationChunkSize) {
|
|
|
|
replicationChunkSize = sourceModel.settings.replicationChunkSize;
|
|
|
|
}
|
2014-05-06 20:31:23 +00:00
|
|
|
|
2015-04-03 07:26:19 +00:00
|
|
|
assert(
|
|
|
|
changeTrackingEnabled,
|
|
|
|
'You must enable change tracking before replicating'
|
|
|
|
);
|
2014-05-06 20:31:23 +00:00
|
|
|
|
2016-04-01 09:14:26 +00:00
|
|
|
var diff, updates, newSourceCp, newTargetCp;
|
2014-05-14 16:20:04 +00:00
|
|
|
|
2015-04-03 07:26:19 +00:00
|
|
|
var tasks = [
|
|
|
|
checkpoints,
|
|
|
|
getSourceChanges,
|
|
|
|
getDiffFromTarget,
|
|
|
|
createSourceUpdates,
|
2016-04-01 09:14:26 +00:00
|
|
|
bulkUpdate,
|
2015-04-03 07:26:19 +00:00
|
|
|
];
|
2014-05-14 16:20:04 +00:00
|
|
|
|
2015-04-03 07:26:19 +00:00
|
|
|
async.waterfall(tasks, done);
|
2015-03-04 14:00:53 +00:00
|
|
|
|
2015-04-03 07:26:19 +00:00
|
|
|
function getSourceChanges(cb) {
|
2016-11-21 08:48:43 +00:00
|
|
|
utils.downloadInChunks(
|
|
|
|
options.filter,
|
|
|
|
replicationChunkSize,
|
|
|
|
function(filter, pagingCallback) {
|
|
|
|
sourceModel.changes(since.source, filter, pagingCallback);
|
|
|
|
},
|
|
|
|
debug.enabled ? log : cb);
|
2014-05-14 16:20:04 +00:00
|
|
|
|
2015-04-03 07:26:19 +00:00
|
|
|
function log(err, result) {
|
|
|
|
if (err) return cb(err);
|
|
|
|
debug('\tusing source changes');
|
|
|
|
result.forEach(function(it) { debug('\t\t%j', it); });
|
|
|
|
cb(err, result);
|
|
|
|
}
|
2014-05-14 16:20:04 +00:00
|
|
|
}
|
|
|
|
|
2015-04-03 07:26:19 +00:00
|
|
|
function getDiffFromTarget(sourceChanges, cb) {
|
2016-11-21 08:48:43 +00:00
|
|
|
utils.uploadInChunks(
|
|
|
|
sourceChanges,
|
|
|
|
replicationChunkSize,
|
|
|
|
function(smallArray, chunkCallback) {
|
|
|
|
return targetModel.diff(since.target, smallArray, chunkCallback);
|
|
|
|
},
|
|
|
|
debug.enabled ? log : cb);
|
2015-04-03 07:26:19 +00:00
|
|
|
|
|
|
|
function log(err, result) {
|
|
|
|
if (err) return cb(err);
|
|
|
|
if (result.conflicts && result.conflicts.length) {
|
|
|
|
debug('\tdiff conflicts');
|
|
|
|
result.conflicts.forEach(function(d) { debug('\t\t%j', d); });
|
|
|
|
}
|
|
|
|
if (result.deltas && result.deltas.length) {
|
|
|
|
debug('\tdiff deltas');
|
|
|
|
result.deltas.forEach(function(it) { debug('\t\t%j', it); });
|
|
|
|
}
|
|
|
|
cb(err, result);
|
|
|
|
}
|
2015-03-03 13:23:46 +00:00
|
|
|
}
|
2014-05-06 20:31:23 +00:00
|
|
|
|
2015-04-03 07:26:19 +00:00
|
|
|
function createSourceUpdates(_diff, cb) {
|
|
|
|
diff = _diff;
|
|
|
|
diff.conflicts = diff.conflicts || [];
|
2016-11-21 08:48:43 +00:00
|
|
|
|
2015-04-03 07:26:19 +00:00
|
|
|
if (diff && diff.deltas && diff.deltas.length) {
|
|
|
|
debug('\tbuilding a list of updates');
|
2016-11-21 08:48:43 +00:00
|
|
|
utils.uploadInChunks(
|
|
|
|
diff.deltas,
|
|
|
|
replicationChunkSize,
|
|
|
|
function(smallArray, chunkCallback) {
|
|
|
|
return sourceModel.createUpdates(smallArray, chunkCallback);
|
|
|
|
},
|
|
|
|
cb);
|
2015-04-03 07:26:19 +00:00
|
|
|
} else {
|
|
|
|
// nothing to replicate
|
|
|
|
done();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
function bulkUpdate(_updates, cb) {
|
|
|
|
debug('\tstarting bulk update');
|
|
|
|
updates = _updates;
|
2016-11-21 08:48:43 +00:00
|
|
|
utils.uploadInChunks(
|
|
|
|
updates,
|
|
|
|
replicationChunkSize,
|
|
|
|
function(smallArray, chunkCallback) {
|
|
|
|
return targetModel.bulkUpdate(smallArray, options, function(err) {
|
|
|
|
// bulk update is a special case where we want to process all chunks and aggregate all errors
|
|
|
|
chunkCallback(null, err);
|
2014-05-06 20:31:23 +00:00
|
|
|
});
|
2016-11-21 08:48:43 +00:00
|
|
|
},
|
|
|
|
function(notUsed, err) {
|
|
|
|
var conflicts = err && err.details && err.details.conflicts;
|
|
|
|
if (conflicts && err.statusCode == 409) {
|
|
|
|
diff.conflicts = conflicts;
|
|
|
|
// filter out updates that were not applied
|
|
|
|
updates = updates.filter(function(u) {
|
|
|
|
return conflicts
|
|
|
|
.filter(function(d) { return d.modelId === u.change.modelId; })
|
|
|
|
.length === 0;
|
|
|
|
});
|
|
|
|
return cb();
|
|
|
|
}
|
|
|
|
cb(err);
|
|
|
|
});
|
2015-04-03 07:26:19 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
function checkpoints() {
|
|
|
|
var cb = arguments[arguments.length - 1];
|
|
|
|
sourceModel.checkpoint(function(err, source) {
|
|
|
|
if (err) return cb(err);
|
|
|
|
newSourceCp = source.seq;
|
|
|
|
targetModel.checkpoint(function(err, target) {
|
|
|
|
if (err) return cb(err);
|
|
|
|
newTargetCp = target.seq;
|
|
|
|
debug('\tcreated checkpoints');
|
|
|
|
debug('\t\t%s for source model %s', newSourceCp, sourceModel.modelName);
|
|
|
|
debug('\t\t%s for target model %s', newTargetCp, targetModel.modelName);
|
|
|
|
cb();
|
2014-05-06 20:31:23 +00:00
|
|
|
});
|
2015-04-03 07:26:19 +00:00
|
|
|
});
|
2014-05-06 20:31:23 +00:00
|
|
|
}
|
|
|
|
|
2015-04-03 07:26:19 +00:00
|
|
|
function done(err) {
|
|
|
|
if (err) return callback(err);
|
2014-05-06 20:31:23 +00:00
|
|
|
|
2015-04-03 07:26:19 +00:00
|
|
|
debug('\treplication finished');
|
|
|
|
debug('\t\t%s conflict(s) detected', diff.conflicts.length);
|
|
|
|
debug('\t\t%s change(s) applied', updates ? updates.length : 0);
|
|
|
|
debug('\t\tnew checkpoints: { source: %j, target: %j }',
|
|
|
|
newSourceCp, newTargetCp);
|
2014-05-06 20:31:23 +00:00
|
|
|
|
2015-04-03 07:26:19 +00:00
|
|
|
var conflicts = diff.conflicts.map(function(change) {
|
|
|
|
return new Change.Conflict(
|
|
|
|
change.modelId, sourceModel, targetModel
|
|
|
|
);
|
|
|
|
});
|
2014-05-06 20:31:23 +00:00
|
|
|
|
2015-04-03 07:26:19 +00:00
|
|
|
if (conflicts.length) {
|
|
|
|
sourceModel.emit('conflicts', conflicts);
|
|
|
|
}
|
2015-03-16 12:38:37 +00:00
|
|
|
|
2015-04-03 07:26:19 +00:00
|
|
|
if (callback) {
|
2016-11-15 21:46:23 +00:00
|
|
|
var newCheckpoints = {source: newSourceCp, target: newTargetCp};
|
2015-04-03 07:26:19 +00:00
|
|
|
callback(null, conflicts, newCheckpoints, updates);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2015-03-16 12:38:37 +00:00
|
|
|
|
2015-04-03 07:26:19 +00:00
|
|
|
/**
|
|
|
|
* Create an update list (for `Model.bulkUpdate()`) from a delta list
|
|
|
|
* (result of `Change.diff()`).
|
|
|
|
*
|
|
|
|
* @param {Array} deltas
|
|
|
|
* @param {Function} callback
|
|
|
|
*/
|
|
|
|
|
|
|
|
PersistedModel.createUpdates = function(deltas, cb) {
|
|
|
|
var Change = this.getChangeModel();
|
|
|
|
var updates = [];
|
|
|
|
var Model = this;
|
|
|
|
var tasks = [];
|
|
|
|
|
|
|
|
deltas.forEach(function(change) {
|
|
|
|
change = new Change(change);
|
|
|
|
var type = change.type();
|
2016-11-15 21:46:23 +00:00
|
|
|
var update = {type: type, change: change};
|
2015-04-03 07:26:19 +00:00
|
|
|
switch (type) {
|
2015-03-16 12:38:37 +00:00
|
|
|
case Change.CREATE:
|
2015-04-03 07:26:19 +00:00
|
|
|
case Change.UPDATE:
|
2015-03-16 12:38:37 +00:00
|
|
|
tasks.push(function(cb) {
|
2015-04-03 07:26:19 +00:00
|
|
|
Model.findById(change.modelId, function(err, inst) {
|
|
|
|
if (err) return cb(err);
|
|
|
|
if (!inst) {
|
|
|
|
return cb &&
|
2016-06-07 14:48:28 +00:00
|
|
|
cb(new Error(g.f('Missing data for change: %s', change.modelId)));
|
2015-04-03 07:26:19 +00:00
|
|
|
}
|
|
|
|
if (inst.toObject) {
|
|
|
|
update.data = inst.toObject();
|
|
|
|
} else {
|
|
|
|
update.data = inst;
|
|
|
|
}
|
|
|
|
updates.push(update);
|
|
|
|
cb();
|
|
|
|
});
|
2015-03-16 12:38:37 +00:00
|
|
|
});
|
|
|
|
break;
|
|
|
|
case Change.DELETE:
|
2015-04-03 07:26:19 +00:00
|
|
|
updates.push(update);
|
2015-03-16 12:38:37 +00:00
|
|
|
break;
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
|
|
|
async.parallel(tasks, function(err) {
|
2015-04-03 07:26:19 +00:00
|
|
|
if (err) return cb(err);
|
|
|
|
cb(null, updates);
|
|
|
|
});
|
|
|
|
};
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Apply an update list.
|
|
|
|
*
|
|
|
|
* **Note: this is not atomic**
|
|
|
|
*
|
|
|
|
* @param {Array} updates An updates list, usually from [createUpdates()](#persistedmodel-createupdates).
|
2016-11-15 02:02:23 +00:00
|
|
|
* @param {Object} [options] An optional options object to pass to underlying data-access calls.
|
2015-04-03 07:26:19 +00:00
|
|
|
* @param {Function} callback Callback function.
|
|
|
|
*/
|
|
|
|
|
2016-11-15 02:02:23 +00:00
|
|
|
PersistedModel.bulkUpdate = function(updates, options, callback) {
|
2015-04-03 07:26:19 +00:00
|
|
|
var tasks = [];
|
|
|
|
var Model = this;
|
|
|
|
var Change = this.getChangeModel();
|
|
|
|
var conflicts = [];
|
|
|
|
|
2016-11-15 02:02:23 +00:00
|
|
|
var lastArg = arguments[arguments.length - 1];
|
|
|
|
|
|
|
|
if (typeof lastArg === 'function' && arguments.length > 1) {
|
|
|
|
callback = lastArg;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (typeof options === 'function') {
|
|
|
|
options = {};
|
|
|
|
}
|
|
|
|
|
|
|
|
options = options || {};
|
|
|
|
|
2015-04-03 07:26:19 +00:00
|
|
|
buildLookupOfAffectedModelData(Model, updates, function(err, currentMap) {
|
2015-03-16 12:38:37 +00:00
|
|
|
if (err) return callback(err);
|
2015-04-03 07:26:19 +00:00
|
|
|
|
|
|
|
updates.forEach(function(update) {
|
|
|
|
var id = update.change.modelId;
|
|
|
|
var current = currentMap[id];
|
|
|
|
switch (update.type) {
|
|
|
|
case Change.UPDATE:
|
|
|
|
tasks.push(function(cb) {
|
2016-11-15 02:02:23 +00:00
|
|
|
applyUpdate(Model, id, current, update.data, update.change, conflicts, options, cb);
|
2015-04-03 07:26:19 +00:00
|
|
|
});
|
|
|
|
break;
|
|
|
|
|
|
|
|
case Change.CREATE:
|
|
|
|
tasks.push(function(cb) {
|
2016-11-15 02:02:23 +00:00
|
|
|
applyCreate(Model, id, current, update.data, update.change, conflicts, options, cb);
|
2015-04-03 07:26:19 +00:00
|
|
|
});
|
|
|
|
break;
|
|
|
|
case Change.DELETE:
|
|
|
|
tasks.push(function(cb) {
|
2016-11-15 02:02:23 +00:00
|
|
|
applyDelete(Model, id, current, update.change, conflicts, options, cb);
|
2015-04-03 07:26:19 +00:00
|
|
|
});
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
|
|
|
async.parallel(tasks, function(err) {
|
|
|
|
if (err) return callback(err);
|
|
|
|
if (conflicts.length) {
|
2016-06-07 14:48:28 +00:00
|
|
|
err = new Error(g.f('Conflict'));
|
2015-04-03 07:26:19 +00:00
|
|
|
err.statusCode = 409;
|
2016-11-15 21:46:23 +00:00
|
|
|
err.details = {conflicts: conflicts};
|
2015-04-03 07:26:19 +00:00
|
|
|
return callback(err);
|
|
|
|
}
|
|
|
|
callback();
|
|
|
|
});
|
2015-03-16 12:38:37 +00:00
|
|
|
});
|
2015-04-03 07:26:19 +00:00
|
|
|
};
|
2015-03-16 12:38:37 +00:00
|
|
|
|
2015-04-03 07:26:19 +00:00
|
|
|
function buildLookupOfAffectedModelData(Model, updates, callback) {
|
|
|
|
var idName = Model.dataSource.idName(Model.modelName);
|
|
|
|
var affectedIds = updates.map(function(u) { return u.change.modelId; });
|
|
|
|
var whereAffected = {};
|
2016-11-15 21:46:23 +00:00
|
|
|
whereAffected[idName] = {inq: affectedIds};
|
|
|
|
Model.find({where: whereAffected}, function(err, affectedList) {
|
2015-04-03 07:26:19 +00:00
|
|
|
if (err) return callback(err);
|
|
|
|
var dataLookup = {};
|
|
|
|
affectedList.forEach(function(it) {
|
|
|
|
dataLookup[it[idName]] = it;
|
|
|
|
});
|
|
|
|
callback(null, dataLookup);
|
2015-03-16 12:38:37 +00:00
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2016-11-15 02:02:23 +00:00
|
|
|
function applyUpdate(Model, id, current, data, change, conflicts, options, cb) {
|
2015-04-03 07:26:19 +00:00
|
|
|
var Change = Model.getChangeModel();
|
|
|
|
var rev = current ? Change.revisionForInst(current) : null;
|
|
|
|
|
|
|
|
if (rev !== change.prev) {
|
|
|
|
debug('Detected non-rectified change of %s %j',
|
|
|
|
Model.modelName, id);
|
|
|
|
debug('\tExpected revision: %s', change.rev);
|
|
|
|
debug('\tActual revision: %s', rev);
|
|
|
|
conflicts.push(change);
|
|
|
|
return Change.rectifyModelChanges(Model.modelName, [id], cb);
|
2014-05-06 20:31:23 +00:00
|
|
|
}
|
2015-03-16 12:38:37 +00:00
|
|
|
|
2015-04-03 07:26:19 +00:00
|
|
|
// TODO(bajtos) modify `data` so that it instructs
|
|
|
|
// the connector to remove any properties included in "inst"
|
|
|
|
// but not included in `data`
|
|
|
|
// See https://github.com/strongloop/loopback/issues/1215
|
2015-03-16 12:38:37 +00:00
|
|
|
|
2016-11-15 02:02:23 +00:00
|
|
|
Model.updateAll(current.toObject(), data, options, function(err, result) {
|
2015-04-03 07:26:19 +00:00
|
|
|
if (err) return cb(err);
|
2015-03-16 12:38:37 +00:00
|
|
|
|
2015-04-03 07:26:19 +00:00
|
|
|
var count = result && result.count;
|
|
|
|
switch (count) {
|
|
|
|
case 1:
|
|
|
|
// The happy path, exactly one record was updated
|
|
|
|
return cb();
|
2015-03-16 12:38:37 +00:00
|
|
|
|
2015-04-03 07:26:19 +00:00
|
|
|
case 0:
|
|
|
|
debug('UpdateAll detected non-rectified change of %s %j',
|
|
|
|
Model.modelName, id);
|
|
|
|
conflicts.push(change);
|
|
|
|
// NOTE(bajtos) updateAll triggers change rectification
|
|
|
|
// for all model instances, even when no records were updated,
|
|
|
|
// thus we don't need to rectify explicitly ourselves
|
|
|
|
return cb();
|
2015-03-16 12:38:37 +00:00
|
|
|
|
2015-04-03 07:26:19 +00:00
|
|
|
case undefined:
|
|
|
|
case null:
|
|
|
|
return cb(new Error(
|
2016-06-07 14:48:28 +00:00
|
|
|
g.f('Cannot apply bulk updates, ' +
|
2015-04-03 07:26:19 +00:00
|
|
|
'the connector does not correctly report ' +
|
2016-06-07 14:48:28 +00:00
|
|
|
'the number of updated records.')));
|
2015-04-03 07:26:19 +00:00
|
|
|
|
|
|
|
default:
|
|
|
|
debug('%s.updateAll modified unexpected number of instances: %j',
|
|
|
|
Model.modelName, count);
|
|
|
|
return cb(new Error(
|
2016-06-07 14:48:28 +00:00
|
|
|
g.f('Bulk update failed, the connector has modified unexpected ' +
|
|
|
|
'number of records: %s', JSON.stringify(count))));
|
2015-04-03 07:26:19 +00:00
|
|
|
}
|
|
|
|
});
|
2015-03-16 12:38:37 +00:00
|
|
|
}
|
|
|
|
|
2016-11-15 02:02:23 +00:00
|
|
|
function applyCreate(Model, id, current, data, change, conflicts, options, cb) {
|
|
|
|
Model.create(data, options, function(createErr) {
|
2015-04-03 07:26:19 +00:00
|
|
|
if (!createErr) return cb();
|
|
|
|
|
|
|
|
// We don't have a reliable way how to detect the situation
|
|
|
|
// where he model was not create because of a duplicate id
|
|
|
|
// The workaround is to query the DB to check if the model already exists
|
|
|
|
Model.findById(id, function(findErr, inst) {
|
|
|
|
if (findErr || !inst) {
|
|
|
|
// There isn't any instance with the same id, thus there isn't
|
|
|
|
// any conflict and we just report back the original error.
|
|
|
|
return cb(createErr);
|
|
|
|
}
|
|
|
|
|
|
|
|
return conflict();
|
|
|
|
});
|
|
|
|
});
|
|
|
|
|
|
|
|
function conflict() {
|
|
|
|
// The instance already exists - report a conflict
|
|
|
|
debug('Detected non-rectified new instance of %s %j',
|
|
|
|
Model.modelName, id);
|
|
|
|
conflicts.push(change);
|
|
|
|
|
|
|
|
var Change = Model.getChangeModel();
|
|
|
|
return Change.rectifyModelChanges(Model.modelName, [id], cb);
|
2015-03-16 12:38:37 +00:00
|
|
|
}
|
2015-04-03 07:26:19 +00:00
|
|
|
}
|
2014-05-06 20:31:23 +00:00
|
|
|
|
2016-11-15 02:02:23 +00:00
|
|
|
function applyDelete(Model, id, current, change, conflicts, options, cb) {
|
2015-04-03 07:26:19 +00:00
|
|
|
if (!current) {
|
|
|
|
// The instance was either already deleted or not created at all,
|
|
|
|
// we are done.
|
|
|
|
return cb();
|
|
|
|
}
|
2014-05-06 20:31:23 +00:00
|
|
|
|
2015-04-03 07:26:19 +00:00
|
|
|
var Change = Model.getChangeModel();
|
|
|
|
var rev = Change.revisionForInst(current);
|
|
|
|
if (rev !== change.prev) {
|
|
|
|
debug('Detected non-rectified change of %s %j',
|
|
|
|
Model.modelName, id);
|
|
|
|
debug('\tExpected revision: %s', change.rev);
|
|
|
|
debug('\tActual revision: %s', rev);
|
|
|
|
conflicts.push(change);
|
|
|
|
return Change.rectifyModelChanges(Model.modelName, [id], cb);
|
|
|
|
}
|
2014-05-06 20:31:23 +00:00
|
|
|
|
2016-11-15 02:02:23 +00:00
|
|
|
Model.deleteAll(current.toObject(), options, function(err, result) {
|
2015-04-03 07:26:19 +00:00
|
|
|
if (err) return cb(err);
|
2014-05-06 20:31:23 +00:00
|
|
|
|
2015-04-03 07:26:19 +00:00
|
|
|
var count = result && result.count;
|
|
|
|
switch (count) {
|
|
|
|
case 1:
|
|
|
|
// The happy path, exactly one record was updated
|
|
|
|
return cb();
|
2014-05-06 20:31:23 +00:00
|
|
|
|
2015-04-03 07:26:19 +00:00
|
|
|
case 0:
|
|
|
|
debug('DeleteAll detected non-rectified change of %s %j',
|
|
|
|
Model.modelName, id);
|
|
|
|
conflicts.push(change);
|
|
|
|
// NOTE(bajtos) deleteAll triggers change rectification
|
|
|
|
// for all model instances, even when no records were updated,
|
|
|
|
// thus we don't need to rectify explicitly ourselves
|
|
|
|
return cb();
|
2014-05-06 20:31:23 +00:00
|
|
|
|
2015-04-03 07:26:19 +00:00
|
|
|
case undefined:
|
|
|
|
case null:
|
|
|
|
return cb(new Error(
|
2016-06-07 14:48:28 +00:00
|
|
|
g.f('Cannot apply bulk updates, ' +
|
2015-04-03 07:26:19 +00:00
|
|
|
'the connector does not correctly report ' +
|
2016-06-07 14:48:28 +00:00
|
|
|
'the number of deleted records.')));
|
2015-04-03 07:26:19 +00:00
|
|
|
|
|
|
|
default:
|
|
|
|
debug('%s.deleteAll modified unexpected number of instances: %j',
|
|
|
|
Model.modelName, count);
|
|
|
|
return cb(new Error(
|
2016-06-07 14:48:28 +00:00
|
|
|
g.f('Bulk update failed, the connector has deleted unexpected ' +
|
|
|
|
'number of records: %s', JSON.stringify(count))));
|
2015-04-03 07:26:19 +00:00
|
|
|
}
|
|
|
|
});
|
2014-05-06 20:31:23 +00:00
|
|
|
}
|
|
|
|
|
2015-04-03 07:26:19 +00:00
|
|
|
/**
|
|
|
|
* Get the `Change` model.
|
|
|
|
* Throws an error if the change model is not correctly setup.
|
|
|
|
* @return {Change}
|
|
|
|
*/
|
2014-05-06 20:31:23 +00:00
|
|
|
|
2015-04-03 07:26:19 +00:00
|
|
|
PersistedModel.getChangeModel = function() {
|
|
|
|
var changeModel = this.Change;
|
|
|
|
var isSetup = changeModel && changeModel.dataSource;
|
2015-02-26 15:29:29 +00:00
|
|
|
|
2015-04-03 14:41:32 +00:00
|
|
|
assert(isSetup, 'Cannot get a setup Change model for ' + this.modelName);
|
2014-05-06 20:31:23 +00:00
|
|
|
|
2015-04-03 07:26:19 +00:00
|
|
|
return changeModel;
|
|
|
|
};
|
2014-05-06 20:31:23 +00:00
|
|
|
|
2015-04-03 07:26:19 +00:00
|
|
|
/**
|
|
|
|
* Get the source identifier for this model or dataSource.
|
|
|
|
*
|
|
|
|
* @callback {Function} callback Callback function called with `(err, id)` arguments.
|
2016-11-04 20:47:12 +00:00
|
|
|
* @param {Error} err Error object; see [Error object](http://loopback.io/doc/en/lb2/Error-object.html).
|
2015-04-03 07:26:19 +00:00
|
|
|
* @param {String} sourceId Source identifier for the model or dataSource.
|
|
|
|
*/
|
|
|
|
|
|
|
|
PersistedModel.getSourceId = function(cb) {
|
|
|
|
var dataSource = this.dataSource;
|
|
|
|
if (!dataSource) {
|
|
|
|
this.once('dataSourceAttached', this.getSourceId.bind(this, cb));
|
|
|
|
}
|
|
|
|
assert(
|
|
|
|
dataSource.connector.name,
|
|
|
|
'Model.getSourceId: cannot get id without dataSource.connector.name'
|
|
|
|
);
|
|
|
|
var id = [dataSource.connector.name, this.modelName].join('-');
|
|
|
|
cb(null, id);
|
|
|
|
};
|
2014-05-06 20:31:23 +00:00
|
|
|
|
2015-04-03 07:26:19 +00:00
|
|
|
/**
|
|
|
|
* Enable the tracking of changes made to the model. Usually for replication.
|
|
|
|
*/
|
|
|
|
|
|
|
|
PersistedModel.enableChangeTracking = function() {
|
|
|
|
var Model = this;
|
|
|
|
var Change = this.Change || this._defineChangeModel();
|
|
|
|
var cleanupInterval = Model.settings.changeCleanupInterval || 30000;
|
|
|
|
|
|
|
|
assert(this.dataSource, 'Cannot enableChangeTracking(): ' + this.modelName +
|
|
|
|
' is not attached to a dataSource');
|
|
|
|
|
|
|
|
var idName = this.getIdName();
|
|
|
|
var idProp = this.definition.properties[idName];
|
|
|
|
var idType = idProp && idProp.type;
|
|
|
|
var idDefn = idProp && idProp.defaultFn;
|
|
|
|
if (idType !== String || !(idDefn === 'uuid' || idDefn === 'guid')) {
|
|
|
|
deprecated('The model ' + this.modelName + ' is tracking changes, ' +
|
2016-11-21 08:19:11 +00:00
|
|
|
'which requires a string id with GUID/UUID default value.');
|
2015-04-03 07:26:19 +00:00
|
|
|
}
|
2014-05-06 20:31:23 +00:00
|
|
|
|
2015-04-03 07:26:19 +00:00
|
|
|
Model.observe('after save', rectifyOnSave);
|
|
|
|
|
|
|
|
Model.observe('after delete', rectifyOnDelete);
|
|
|
|
|
2016-11-21 08:19:11 +00:00
|
|
|
// Only run if the run time is server
|
|
|
|
// Can switch off cleanup by setting the interval to -1
|
|
|
|
if (runtime.isServer && cleanupInterval > 0) {
|
2015-04-03 07:26:19 +00:00
|
|
|
// initial cleanup
|
|
|
|
cleanup();
|
|
|
|
|
|
|
|
// cleanup
|
|
|
|
setInterval(cleanup, cleanupInterval);
|
|
|
|
}
|
|
|
|
|
|
|
|
function cleanup() {
|
|
|
|
Model.rectifyAllChanges(function(err) {
|
|
|
|
if (err) {
|
|
|
|
Model.handleChangeError(err, 'cleanup');
|
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
|
|
|
};
|
2014-05-06 20:31:23 +00:00
|
|
|
|
2015-04-03 07:26:19 +00:00
|
|
|
function rectifyOnSave(ctx, next) {
|
2015-09-17 16:58:52 +00:00
|
|
|
var instance = ctx.instance || ctx.currentInstance;
|
|
|
|
var id = instance ? instance.getId() :
|
|
|
|
getIdFromWhereByModelId(ctx.Model, ctx.where);
|
|
|
|
|
2015-12-17 13:13:47 +00:00
|
|
|
if (debug.enabled) {
|
|
|
|
debug('rectifyOnSave %s -> ' + (id ? 'id %j' : '%s'),
|
|
|
|
ctx.Model.modelName, id ? id : 'ALL');
|
|
|
|
debug('context instance:%j currentInstance:%j where:%j data %j',
|
|
|
|
ctx.instance, ctx.currentInstance, ctx.where, ctx.data);
|
|
|
|
}
|
|
|
|
|
2017-12-05 15:49:50 +00:00
|
|
|
if (id != null) {
|
2015-09-17 16:58:52 +00:00
|
|
|
ctx.Model.rectifyChange(id, reportErrorAndNext);
|
2015-04-03 07:26:19 +00:00
|
|
|
} else {
|
|
|
|
ctx.Model.rectifyAllChanges(reportErrorAndNext);
|
|
|
|
}
|
|
|
|
|
|
|
|
function reportErrorAndNext(err) {
|
2014-11-04 07:13:21 +00:00
|
|
|
if (err) {
|
2015-04-03 07:26:19 +00:00
|
|
|
ctx.Model.handleChangeError(err, 'after save');
|
2014-11-04 07:13:21 +00:00
|
|
|
}
|
2015-04-03 07:26:19 +00:00
|
|
|
next();
|
|
|
|
}
|
2014-05-06 20:31:23 +00:00
|
|
|
}
|
|
|
|
|
2015-04-03 07:26:19 +00:00
|
|
|
function rectifyOnDelete(ctx, next) {
|
|
|
|
var id = ctx.instance ? ctx.instance.getId() :
|
|
|
|
getIdFromWhereByModelId(ctx.Model, ctx.where);
|
2015-02-20 18:28:33 +00:00
|
|
|
|
2015-12-17 13:13:47 +00:00
|
|
|
if (debug.enabled) {
|
|
|
|
debug('rectifyOnDelete %s -> ' + (id ? 'id %j' : '%s'),
|
|
|
|
ctx.Model.modelName, id ? id : 'ALL');
|
|
|
|
debug('context instance:%j where:%j', ctx.instance, ctx.where);
|
|
|
|
}
|
|
|
|
|
2017-12-05 15:49:50 +00:00
|
|
|
if (id != null) {
|
2015-04-03 07:26:19 +00:00
|
|
|
ctx.Model.rectifyChange(id, reportErrorAndNext);
|
|
|
|
} else {
|
|
|
|
ctx.Model.rectifyAllChanges(reportErrorAndNext);
|
|
|
|
}
|
|
|
|
|
|
|
|
function reportErrorAndNext(err) {
|
|
|
|
if (err) {
|
|
|
|
ctx.Model.handleChangeError(err, 'after delete');
|
|
|
|
}
|
|
|
|
next();
|
2015-02-20 18:28:33 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-04-03 07:26:19 +00:00
|
|
|
function getIdFromWhereByModelId(Model, where) {
|
|
|
|
var idName = Model.getIdName();
|
2015-12-17 21:40:19 +00:00
|
|
|
if (!(idName in where)) return undefined;
|
2015-02-20 18:28:33 +00:00
|
|
|
|
2015-04-03 07:26:19 +00:00
|
|
|
var id = where[idName];
|
|
|
|
// TODO(bajtos) support object values that are not LB conditions
|
|
|
|
if (typeof id === 'string' || typeof id === 'number') {
|
|
|
|
return id;
|
2015-02-20 18:28:33 +00:00
|
|
|
}
|
2015-04-03 07:26:19 +00:00
|
|
|
return undefined;
|
2015-02-20 18:28:33 +00:00
|
|
|
}
|
|
|
|
|
2015-04-03 07:26:19 +00:00
|
|
|
PersistedModel._defineChangeModel = function() {
|
2015-04-01 21:50:36 +00:00
|
|
|
var BaseChangeModel = this.registry.getModel('Change');
|
2015-04-03 07:26:19 +00:00
|
|
|
assert(BaseChangeModel,
|
|
|
|
'Change model must be defined before enabling change replication');
|
2015-02-20 18:28:33 +00:00
|
|
|
|
2016-11-21 08:13:16 +00:00
|
|
|
const additionalChangeModelProperties =
|
|
|
|
this.settings.additionalChangeModelProperties || {};
|
|
|
|
|
2015-04-03 07:26:19 +00:00
|
|
|
this.Change = BaseChangeModel.extend(this.modelName + '-change',
|
2016-11-21 08:13:16 +00:00
|
|
|
additionalChangeModelProperties,
|
|
|
|
{trackModel: this}
|
2015-04-03 07:26:19 +00:00
|
|
|
);
|
2015-02-20 18:28:33 +00:00
|
|
|
|
2015-04-03 14:41:32 +00:00
|
|
|
if (this.dataSource) {
|
|
|
|
attachRelatedModels(this);
|
|
|
|
}
|
|
|
|
|
2016-01-25 09:36:51 +00:00
|
|
|
// Re-attach related models whenever our datasource is changed.
|
2015-04-08 09:52:58 +00:00
|
|
|
var self = this;
|
|
|
|
this.on('dataSourceAttached', function() {
|
|
|
|
attachRelatedModels(self);
|
|
|
|
});
|
|
|
|
|
2015-04-03 07:26:19 +00:00
|
|
|
return this.Change;
|
2015-04-03 14:41:32 +00:00
|
|
|
|
|
|
|
function attachRelatedModels(self) {
|
|
|
|
self.Change.attachTo(self.dataSource);
|
|
|
|
self.Change.getCheckpointModel().attachTo(self.dataSource);
|
|
|
|
}
|
2015-04-03 07:26:19 +00:00
|
|
|
};
|
2014-11-04 07:13:21 +00:00
|
|
|
|
2015-04-03 07:26:19 +00:00
|
|
|
PersistedModel.rectifyAllChanges = function(callback) {
|
|
|
|
this.getChangeModel().rectifyAll(callback);
|
|
|
|
};
|
2014-05-10 00:19:32 +00:00
|
|
|
|
2015-04-03 07:26:19 +00:00
|
|
|
/**
|
|
|
|
* Handle a change error. Override this method in a subclassing model to customize
|
|
|
|
* change error handling.
|
|
|
|
*
|
2016-11-04 20:47:12 +00:00
|
|
|
* @param {Error} err Error object; see [Error object](http://loopback.io/doc/en/lb2/Error-object.html).
|
2015-04-03 07:26:19 +00:00
|
|
|
*/
|
2014-05-10 00:19:32 +00:00
|
|
|
|
2015-04-03 07:26:19 +00:00
|
|
|
PersistedModel.handleChangeError = function(err, operationName) {
|
|
|
|
if (!err) return;
|
|
|
|
this.emit('error', err, operationName);
|
|
|
|
};
|
2014-05-10 00:19:32 +00:00
|
|
|
|
2015-04-03 07:26:19 +00:00
|
|
|
/**
|
|
|
|
* Specify that a change to the model with the given ID has occurred.
|
|
|
|
*
|
|
|
|
* @param {*} id The ID of the model that has changed.
|
|
|
|
* @callback {Function} callback
|
|
|
|
* @param {Error} err
|
|
|
|
*/
|
|
|
|
|
|
|
|
PersistedModel.rectifyChange = function(id, callback) {
|
|
|
|
var Change = this.getChangeModel();
|
|
|
|
Change.rectifyModelChanges(this.modelName, [id], callback);
|
|
|
|
};
|
2014-05-10 00:19:32 +00:00
|
|
|
|
2015-04-09 10:44:29 +00:00
|
|
|
PersistedModel.findLastChange = function(id, cb) {
|
|
|
|
var Change = this.getChangeModel();
|
2016-11-15 21:46:23 +00:00
|
|
|
Change.findOne({where: {modelId: id}}, cb);
|
2015-04-09 10:44:29 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
PersistedModel.updateLastChange = function(id, data, cb) {
|
|
|
|
var self = this;
|
|
|
|
this.findLastChange(id, function(err, inst) {
|
|
|
|
if (err) return cb(err);
|
|
|
|
if (!inst) {
|
2016-06-07 14:48:28 +00:00
|
|
|
err = new Error(g.f('No change record found for %s with id %s',
|
|
|
|
self.modelName, id));
|
2015-04-09 10:44:29 +00:00
|
|
|
err.statusCode = 404;
|
|
|
|
return cb(err);
|
|
|
|
}
|
|
|
|
|
|
|
|
inst.updateAttributes(data, cb);
|
|
|
|
});
|
|
|
|
};
|
|
|
|
|
2015-07-09 20:30:50 +00:00
|
|
|
/**
|
2016-11-04 20:47:12 +00:00
|
|
|
* Create a change stream. [See here for more info](http://loopback.io/doc/en/lb2/Realtime-server-sent-events.html)
|
2015-07-09 20:30:50 +00:00
|
|
|
*
|
|
|
|
* @param {Object} options
|
|
|
|
* @param {Object} options.where Only changes to models matching this where filter will be included in the `ChangeStream`.
|
|
|
|
* @callback {Function} callback
|
|
|
|
* @param {Error} err
|
|
|
|
* @param {ChangeStream} changes
|
|
|
|
*/
|
|
|
|
|
|
|
|
PersistedModel.createChangeStream = function(options, cb) {
|
|
|
|
if (typeof options === 'function') {
|
|
|
|
cb = options;
|
|
|
|
options = undefined;
|
|
|
|
}
|
|
|
|
|
|
|
|
var idName = this.getIdName();
|
|
|
|
var Model = this;
|
2016-11-15 21:46:23 +00:00
|
|
|
var changes = new PassThrough({objectMode: true});
|
2015-07-09 20:30:50 +00:00
|
|
|
|
2017-07-04 21:01:24 +00:00
|
|
|
changes._destroy = function() {
|
|
|
|
changes.end();
|
|
|
|
changes.emit('end');
|
|
|
|
changes.emit('close');
|
2015-07-09 20:30:50 +00:00
|
|
|
};
|
|
|
|
|
2017-07-04 21:01:24 +00:00
|
|
|
changes.destroy = changes.destroy || changes._destroy; // node 8 compability
|
|
|
|
|
|
|
|
changes.on('error', removeHandlers);
|
|
|
|
changes.on('close', removeHandlers);
|
|
|
|
changes.on('finish', removeHandlers);
|
|
|
|
changes.on('end', removeHandlers);
|
2015-07-09 20:30:50 +00:00
|
|
|
|
|
|
|
process.nextTick(function() {
|
|
|
|
cb(null, changes);
|
|
|
|
});
|
|
|
|
|
2017-07-04 21:01:24 +00:00
|
|
|
Model.observe('after save', changeHandler);
|
|
|
|
Model.observe('after delete', deleteHandler);
|
2015-07-09 20:30:50 +00:00
|
|
|
|
2017-07-04 21:01:24 +00:00
|
|
|
function changeHandler(ctx, next) {
|
|
|
|
var change = createChangeObject(ctx, 'save');
|
|
|
|
changes.write(change);
|
2015-07-09 20:30:50 +00:00
|
|
|
|
2017-07-04 21:01:24 +00:00
|
|
|
next();
|
|
|
|
};
|
2015-07-09 20:30:50 +00:00
|
|
|
|
2017-07-04 21:01:24 +00:00
|
|
|
function deleteHandler(ctx, next) {
|
|
|
|
var change = createChangeObject(ctx, 'delete');
|
|
|
|
changes.write(change);
|
2015-07-09 20:30:50 +00:00
|
|
|
|
2017-07-04 21:01:24 +00:00
|
|
|
next();
|
|
|
|
};
|
2015-07-09 20:30:50 +00:00
|
|
|
|
2017-07-04 21:01:24 +00:00
|
|
|
function createChangeObject(ctx, type) {
|
|
|
|
var where = ctx.where;
|
|
|
|
var data = ctx.instance || ctx.data;
|
|
|
|
var whereId = where && where[idName];
|
2015-07-09 20:30:50 +00:00
|
|
|
|
2017-07-04 21:01:24 +00:00
|
|
|
// the data includes the id
|
|
|
|
// or the where includes the id
|
|
|
|
var target;
|
2015-07-09 20:30:50 +00:00
|
|
|
|
2017-07-04 21:01:24 +00:00
|
|
|
if (data && (data[idName] || data[idName] === 0)) {
|
|
|
|
target = data[idName];
|
|
|
|
} else if (where && (where[idName] || where[idName] === 0)) {
|
|
|
|
target = where[idName];
|
|
|
|
}
|
2015-07-09 20:30:50 +00:00
|
|
|
|
2017-07-04 21:01:24 +00:00
|
|
|
var hasTarget = target === 0 || !!target;
|
2015-07-09 20:30:50 +00:00
|
|
|
|
2017-07-04 21:01:24 +00:00
|
|
|
var change = {
|
|
|
|
target: target,
|
|
|
|
where: where,
|
|
|
|
data: data,
|
2015-07-09 20:30:50 +00:00
|
|
|
};
|
2017-07-04 21:01:24 +00:00
|
|
|
|
|
|
|
switch (type) {
|
|
|
|
case 'save':
|
|
|
|
if (ctx.isNewInstance === undefined) {
|
|
|
|
change.type = hasTarget ? 'update' : 'create';
|
|
|
|
} else {
|
|
|
|
change.type = ctx.isNewInstance ? 'create' : 'update';
|
|
|
|
}
|
|
|
|
|
|
|
|
break;
|
|
|
|
case 'delete':
|
|
|
|
change.type = 'remove';
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
|
|
|
|
return change;
|
|
|
|
}
|
|
|
|
|
|
|
|
function removeHandlers() {
|
|
|
|
Model.removeObserver('after save', changeHandler);
|
|
|
|
Model.removeObserver('after delete', deleteHandler);
|
2015-07-09 20:30:50 +00:00
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2016-11-21 08:13:16 +00:00
|
|
|
/**
|
|
|
|
* Get the filter for searching related changes.
|
|
|
|
*
|
|
|
|
* Models should override this function to copy properties
|
|
|
|
* from the model instance filter into the change search filter.
|
|
|
|
*
|
|
|
|
* ```js
|
|
|
|
* module.exports = (TargetModel, config) => {
|
|
|
|
* TargetModel.createChangeFilter = function(since, modelFilter) {
|
|
|
|
* const filter = this.base.createChangeFilter.apply(this, arguments);
|
|
|
|
* if (modelFilter && modelFilter.where && modelFilter.where.tenantId) {
|
|
|
|
* filter.where.tenantId = modelFilter.where.tenantId;
|
|
|
|
* }
|
|
|
|
* return filter;
|
|
|
|
* };
|
|
|
|
* };
|
|
|
|
* ```
|
|
|
|
*
|
|
|
|
* @param {Number} since Return only changes since this checkpoint.
|
|
|
|
* @param {Object} modelFilter Filter describing which model instances to
|
|
|
|
* include in the list of changes.
|
|
|
|
* @returns {Object} The filter object to pass to `Change.find()`. Default:
|
|
|
|
* ```
|
|
|
|
* {where: {checkpoint: {gte: since}, modelName: this.modelName}}
|
|
|
|
* ```
|
|
|
|
*/
|
|
|
|
PersistedModel.createChangeFilter = function(since, modelFilter) {
|
|
|
|
return {
|
|
|
|
where: {
|
|
|
|
checkpoint: {gte: since},
|
|
|
|
modelName: this.modelName,
|
|
|
|
},
|
|
|
|
};
|
|
|
|
};
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Add custom data to the Change instance.
|
|
|
|
*
|
|
|
|
* Models should override this function to duplicate model instance properties
|
|
|
|
* to the Change instance properties, typically to allow the changes() method
|
|
|
|
* to filter the changes using these duplicated properties directly while
|
|
|
|
* querying the Change model.
|
|
|
|
*
|
|
|
|
* ```js
|
|
|
|
* module.exports = (TargetModel, config) => {
|
|
|
|
* TargetModel.prototype.fillCustomChangeProperties = function(change, cb) {
|
|
|
|
* var inst = this;
|
|
|
|
* const base = this.constructor.base;
|
|
|
|
* base.prototype.fillCustomChangeProperties.call(this, change, err => {
|
|
|
|
* if (err) return cb(err);
|
|
|
|
*
|
|
|
|
* if (inst && inst.tenantId) {
|
|
|
|
* change.tenantId = inst.tenantId;
|
|
|
|
* } else {
|
|
|
|
* change.tenantId = null;
|
|
|
|
* }
|
|
|
|
*
|
|
|
|
* cb();
|
|
|
|
* });
|
|
|
|
* };
|
|
|
|
* };
|
|
|
|
* ```
|
|
|
|
*
|
|
|
|
* @callback {Function} callback
|
|
|
|
* @param {Error} err Error object; see [Error object](http://loopback.io/doc/en/lb3/Error-object.html).
|
|
|
|
*/
|
|
|
|
PersistedModel.prototype.fillCustomChangeProperties = function(change, cb) {
|
|
|
|
// no-op by default
|
|
|
|
cb();
|
|
|
|
};
|
|
|
|
|
2015-04-03 07:26:19 +00:00
|
|
|
PersistedModel.setup();
|
2014-05-10 00:19:32 +00:00
|
|
|
|
2015-04-03 07:26:19 +00:00
|
|
|
return PersistedModel;
|
2014-10-16 22:54:40 +00:00
|
|
|
};
|