All files / src Document.js

98.99% Statements 98/99
97.18% Branches 69/71
100% Functions 17/17
98.99% Lines 98/99

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

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347                                                98x                                                                                     98x 4x 4x     98x 63x 3x 3x   63x     98x 59x             98x 69x     966x   966x         29x               1x   67x   67x 51x     67x 17x     67x 67x 67x   67x               1x 28x                           1x 8x   8x 3x 3x     8x 1x     7x 4x                     1x 7x   7x 3x 3x     7x       7x 4x                     1x 7x   7x 4x 4x     7x 1x     6x   5x     4x 1x     3x 3x   3x                                     1x   8x 8x 8x   8x 3x 3x     8x 4x 1x     3x 3x   3x 3x       8x                         1x 3x   3x   3x                   1x 66x   66x 64x     2x 2x       66x                   1x     3x 2x 2x     3x   3x 1x     2x   2x                       1x 1x 1x       1x  
/**
 * This is a global callback pattern, called by all asynchronous functions of the Kuzzle object.
 *
 * @callback responseCallback
 * @param {Object} err - Error object, NULL if the query is successful
 * @param {Object} [data] - The content of the query response
 */
 
/**
 * Kuzzle handles documents either as realtime messages or as stored documents.
 * Document is the object representation of one of these documents.
 *
 * Notes:
 *   - this constructor may be called either with a documentId, a content, neither or both.
 *   - providing a documentID to the constructor will automatically call refresh, unless a content is also provided
 *
 *
 * @param {Collection} collection - an instanciated Collection object
 * @param {string} [documentId] - ID of an existing document
 * @param {object} [content] - Initializes this document with the provided content
 * @param {object} [meta] - Initializes this document with the provided meta
 * @constructor
 */
function Document(collection, documentId, content, meta) {
  Object.defineProperties(this, {
    // read-only properties
    collection: {
      value: collection.collection,
      enumerable: true
    },
    dataCollection: {
      value: collection,
      enumerable: false
    },
    kuzzle: {
      value: collection.kuzzle,
      enumerable: false
    },
    // writable properties
    id: {
      value: undefined,
      enumerable: true,
      writable: true
    },
    content: {
      value: {},
      writable: true,
      enumerable: true
    },
    headers: {
      value: JSON.parse(JSON.stringify(collection.headers)),
      enumerable: true,
      writable: true
    },
    version: {
      value: undefined,
      enumerable: true,
      writable: true
    },
    meta: {
      value: meta || {},
      enumerable: true,
      writable: false
    }
  });
 
  // handling provided arguments
  if (!content && documentId && typeof documentId === 'object') {
    content = documentId;
    documentId = null;
  }
 
  if (content) {
    if (content._version) {
      this.version = content._version;
      delete content._version;
    }
    this.setContent(content, true);
  }
 
  if (documentId) {
    Object.defineProperty(this, 'id', {
      value: documentId,
      enumerable: true
    });
  }
 
  // promisifying
  if (this.kuzzle.bluebird) {
    return this.kuzzle.bluebird.promisifyAll(this, {
      suffix: 'Promise',
      filter: function (name, func, target, passes) {
        var whitelist = ['delete', 'refresh', 'save'];
 
        return passes && whitelist.indexOf(name) !== -1;
      }
    });
  }
 
  return this;
}
 
/**
 * Serialize this object into a JSON object
 *
 * @return {object} JSON object representing this document
 */
Document.prototype.serialize = function () {
  var
    data = {};
 
  if (this.id) {
    data._id = this.id;
  }
 
  if (this.version) {
    data._version = this.version;
  }
 
  data.body = this.content;
  data.meta = this.meta;
  data = this.kuzzle.addHeaders(data, this.headers);
 
  return data;
};
 
/**
 * Overrides the toString() method in order to return a serialized version of the document
 *
 * @return {string} serialized version of this object
 */
Document.prototype.toString = function () {
  return JSON.stringify(this.serialize());
};
 
/**
 * Deletes this document in Kuzzle.
 *
 * Takes an optional argument object with the following properties:
 *    - volatile (object, default: null):
 *        Additional information passed to notifications to other users
 *
 * @param {object} [options] - Optional parameters
 * @param {responseCallback} [cb] - Handles the query response
 * @returns {*} this
 */
Document.prototype.delete = function (options, cb) {
  var self = this;
 
  if (!cb && typeof options === 'function') {
    cb = options;
    options = null;
  }
 
  if (!self.id) {
    throw new Error('Document.delete: cannot delete a document without a document ID');
  }
 
  this.kuzzle.query(this.dataCollection.buildQueryArgs('document', 'delete'), this.serialize(), options, cb && function (err) {
    cb(err, err ? undefined : self.id);
  });
};
 
/**
 * Checks if this document exists in Kuzzle.
 *
 * @param {object} [options] - Optional parameters
 * @param {responseCallback} [cb] - Handles the query response
 * @returns {*} this
 */
Document.prototype.exists = function (options, cb) {
  var self = this;
 
  if (!cb && typeof options === 'function') {
    cb = options;
    options = null;
  }
 
  Iif (!self.id) {
    throw new Error('Document.exists: cannot check if the document exists if no id has been provided');
  }
 
  this.kuzzle.query(this.dataCollection.buildQueryArgs('document', 'exists'), this.serialize(), options, cb && function (err, res) {
    cb(err, err ? undefined : res.result);
  });
};
 
/**
 * Replaces the current content with the last version of this document stored in Kuzzle.
 *
 * @param {object} [options] - Optional parameters
 * @param {responseCallback} [cb] - Handles the query response
 * @returns {*} this
 */
Document.prototype.refresh = function (options, cb) {
  var self = this;
 
  if (!cb && typeof options === 'function') {
    cb = options;
    options = null;
  }
 
  if (!self.id) {
    throw new Error('Document.refresh: cannot retrieve a document if no ID has been provided');
  }
 
  this.kuzzle.callbackRequired('Document.refresh', cb);
 
  self.kuzzle.query(self.dataCollection.buildQueryArgs('document', 'get'), {_id: self.id}, options, function (error, res) {
    var newDocument;
 
    if (error) {
      return cb(error);
    }
 
    newDocument = new Document(self.dataCollection, self.id, res.result._source, res.result._meta);
    newDocument.version = res.result._version;
 
    cb(null, newDocument);
  });
};
 
/**
 * Saves this document into Kuzzle.
 *
 * If this is a new document, this function will create it in Kuzzle and the id property will be made available.
 * Otherwise, this method will replace the latest version of this document in Kuzzle by the current content
 * of this object.
 *
 * Takes an optional argument object with the following properties:
 *    - volatile (object, default: null):
 *        Additional information passed to notifications to other users
 *
 * @param {object} [options] - Optional parameters
 * @param {responseCallback} [cb] - Handles the query response
 * @returns {*} this
 */
Document.prototype.save = function (options, cb) {
  var
    data = this.serialize(),
    action = data._id ? 'createOrReplace' : 'create',
    self = this;
 
  if (options && cb === undefined && typeof options === 'function') {
    cb = options;
    options = null;
  }
 
  self.kuzzle.query(this.dataCollection.buildQueryArgs('document', action), data, options, function (error, res) {
    if (error) {
      return cb && cb(error);
    }
 
    self.id = res.result._id;
    self.version = res.result._version;
 
    Eif (cb) {
      cb(null, self);
    }
  });
 
  return self;
};
 
/**
 * Sends the content of this document as a realtime message.
 *
 * Takes an optional argument object with the following properties:
 *    - volatile (object, default: null):
 *        Additional information passed to notifications to other users
 *
 * @param {object} [options] - Optional parameters
 * @returns {*} this
 */
Document.prototype.publish = function (options) {
  var data = this.serialize();
 
  this.kuzzle.query(this.dataCollection.buildQueryArgs('realtime', 'publish'), data, options);
 
  return this;
};
 
/**
 * Replaces the current content with new data.
 * Changes made by this function won’t be applied until the save method is called.
 *
 * @param {object} data - New content
 * @param {boolean} replace - if true: replace this document content with the provided data
 */
Document.prototype.setContent = function (data, replace) {
  var self = this;
 
  if (replace) {
    this.content = data;
  }
  else {
    Object.keys(data).forEach(function (key) {
      self.content[key] = data[key];
    });
  }
 
  return this;
};
 
/**
 * Listens to events concerning this document. Has no effect if the document does not have an ID
 * (i.e. if the document has not yet been created as a persisted document).
 *
 * @param {object} [options] - subscription options
 * @param {responseCallback} cb - callback that will be called each time a change has been detected on this document
 */
Document.prototype.subscribe = function (options, cb) {
  var filters;
 
  if (options && !cb && typeof options === 'function') {
    cb = options;
    options = null;
  }
 
  this.kuzzle.callbackRequired('Document.subscribe', cb);
 
  if (!this.id) {
    throw new Error('Document.subscribe: cannot subscribe to a document if no ID has been provided');
  }
 
  filters = { ids: { values: [this.id] } };
 
  return this.dataCollection.subscribe(filters, options, cb);
};
 
/**
 * Helper function allowing to set headers while chaining calls.
 *
 * If the replace argument is set to true, replace the current headers with the provided content.
 * Otherwise, it appends the content to the current headers, only replacing already existing values
 *
 * @param content - new headers content
 * @param [replace] - default: false = append the content. If true: replace the current headers with tj
 */
Document.prototype.setHeaders = function (content, replace) {
  this.kuzzle.setHeaders.call(this, content, replace);
  return this;
};
 
 
module.exports = Document;