Source: storage/storage-object.js

/**
 * Copyright© 2016, Oracle and/or its affiliates. All rights reserved.
 */


/**
 * Class that represents a storage object resource that can be used to store data.
 * @param storageCollection {StorageCollection}
 * @param json {Object}
 * @constructor
 * @global
 */
function StorageObject(storageCollection, json, utils, platform) {

  utils = utils || mcs._utils;
  platform = platform || mcs.mobileBackendManager.platform;

  var HEADERS = utils.HEADERS;
  var _backend = storageCollection._getBackend();
  var _storageCollection = storageCollection;
  var _payload = null;

  if (json) {
    /**
     * A service generated ID for the StorageObject. The ID is unique in the StorageCollection.
     * @type {String}
     */
    this.id = json.id;

    /**
     * A user-provided name for the StorageObject. A StorageCollection may have multiple StorageObjects with the same name.
     * @type {String}
     */
    this.name = json.name;

    /**
     * The length of data content in bytes stored in the StorageObject.
     * @type {Number}
     */
    this.contentLength = json.contentLength;

    /**
     * The media-type associated with the StorageObject.
     * @type {String}
     */
    this.contentType = json.contentType;

    this._eTag = json.eTag;

    /**
     * The name of the user who created the StorageObject.
     * @type {String}
     */
    this.createdBy = json.createdBy;

    /**
     * Server-generated timestamp when the StorageObject was created.
     * @type {String}
     */
    this.createdOn = json.createdOn;

    /**
     * The name of the user who last updated the StorageObject.
     * @type {String}
     */
    this.modifiedBy = json.modifiedBy;

    /**
     * Server-generated timestamp for when the StorageObject was last updated.
     * @type {String}
     */
    this.modifiedOn = json.modifiedOn;
  }

  /**
   * Returns the current StorageObject payload.
   *
   * @return Current Storage object payload.
   */
  this.getPayload = function(){
    return _payload;
  };


  /**
   * Sets the payload for the StorageObject.
   *
   * @param payload The payload to be associated with StorageObject.
   */
  this.setPayload =function(payload){
    _payload = payload;
  };

  /**
   * Returns the current StorageCollection.
   *
   * @return Current StorageCollection.
   */
  this.getstorageCollection = function(){
    return _storageCollection;
  };

  /**
   * Returns the current StorageObject.
   *
   * @return Current StorageObject.
   */
  this.getStorage = function(){
    return _storageCollection._storage
  };

  /**
   * Loads a StorageObject's contents from an object.
   * @param payload {Object} The object to load from.
   * @example payload: "Hello my name is Mia and this is a sample payload".
   * @param contentType {String} The media-type to associate with the content.
   * @example contentType: "application/json,text/plain".
   */
  this.loadPayload = function(payload, contentType) {

    _payload = payload;
    this.contentType = contentType;

    if(this.contentType == utils.ACCEPT_TYPES.TEXT_PLAIN){
      if(typeof _payload == "string") {
        _payload = payload;
      }
    }
    else if(this.contentType == utils.ACCEPT_TYPES.APPLICATION_JSON){
      if(typeof _payload == "string"){
        _payload = payload;
      }
      else if(typeof _payload == "object"){
        _payload = JSON.stringify(payload);
      }
    }
    this.contentLength = _payload.length;
  };
  /**
   * Sets a StorageObject's display name from an object.
   * @param name {Object} The object's name to be associated with the object.
   * @example name: "JSFile中国人.txt"
   * @returns The object's name in UTC-8 ASCII format.
   */
  this.setDisplayName = function(name){
    this.name = name;
  };

  /**
   * Returns a StorageObject's display name from an object.
   *
   * @returns String object's name decoded if encoded into the MobileBackend.
   */
  this.getDisplayName = function(){
    return this.name;
  };


    /**
     * Callback invoked after successfully downloading data from the StorageObject.
     * @callback StorageObject~readPayloadSuccessCallback
     * @param statusCode {Number} Any HTTP status code returned from the server, if available.
     * @param mobileObject {Object} The downloaded data.
     * @deprecated Use promises instead
     */

    /**
     * Callback invoked on error.
     * @callback StorageObject~errorCallback
     * @param statusCode {Number} Any HTTP status code returned from the server, if available.
     * @param message {String} The HTTP payload from the server, if available, or an error message.
     * @deprecated Use promises instead
     */

    /**
     * Returns the contents of the StorageObject. May result in a download from the service if the contents were not
     * previously downloaded.
     * @param [successCallback] {StorageObject~readPayloadSuccessCallback} Callback invoked on success (deprecated use promises instead).
     * @param [errorCallback] {StorageObject~errorCallback} Callback invoked on error (deprecated use promises instead).
     * @param objectType responseType for the XMLHttpRequest Object.
     * @return {Promise.<StorageObject|NetworkResponse>}
     */
  this.readPayload = function(successCallback, errorCallback, objectType) {
    var payload = this.getPayload();
    if(!payload) {
      // TODO: remove assign when callbacks is replaced with promises
      if(typeof successCallback !== 'function'){
        objectType = successCallback;
      }

      var storageObject = this;

      var headers = _backend.getHttpHeaders(utils.MODULE_NAMES.STORAGE);

      var url = "storage/collections/" + _storageCollection.id + "/objects/" + this.id;

      if(_storageCollection.userId !== null && _storageCollection.getUserIsolated()){
        url += "?user=" + _storageCollection.userId;
      }

      return platform.invokeService({
        method: utils.HTTP_METHODS.GET,
        url: _backend.getPlatformUrl(url),
        headers: headers,
        responseType: objectType || "blob"
      }).then(invokeServiceSuccess,invokeServiceError);
    } else {
      if(successCallback && typeof successCallback === 'function'){
        successCallback(payload);
      }
      return Promise.resolve(payload);
    }

    function invokeServiceSuccess(response) {
      storageObject.setPayload(response.data);
      storageObject.name = decodeURI(response.headers[HEADERS.ORACLE_MOBILE_NAME.toLowerCase()]);
      storageObject._eTag = response.headers[HEADERS.E_TAG.toLowerCase()];
      storageObject.contentLength = response.data.size;
      storageObject.contentType = response.headers[HEADERS.CONTENT_TYPE.toLowerCase()];
      storageObject.createdBy = response.headers[HEADERS.ORACLE_MOBILE_CREATED_BY.toLowerCase()];
      storageObject.createdOn = response.headers[HEADERS.ORACLE_MOBILE_CREATED_ON.toLowerCase()];
      storageObject.modifiedBy = response.headers[HEADERS.ORACLE_MOBILE_MODIFIED_BY.toLowerCase()];
      storageObject.modifiedOn = response.headers[HEADERS.ORACLE_MOBILE_MODIFIED_ON.toLowerCase()];

      if (successCallback && typeof successCallback === 'function') {
        successCallback(storageObject);
      }
      return storageObject;
    }

    function invokeServiceError(response) {
      if(errorCallback) {
        errorCallback(response.statusCode, response.data);
      } else {
        return Promise.reject(response);
      }
    }
  };
}