indexstorage.js 5.72 KB
Newer Older
Sven Franck's avatar
Sven Franck committed
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
/*jslint indent: 2, maxlen: 80, sloppy: true, nomen: true */
/*global jIO: true, localStorage: true, setTimeout: true */
jIO.addStorageType('indexed', function (spec, my) {
  spec = spec || {};
  var that = my.basicStorage(spec, my),
    priv = {},
    validatestate_sub_storage = spec.storage || false,
    storage_object_name = 'jio/indexed_storage_object',
    storage_file_object_name,
    super_serialized = that.serialized;

  priv.sub_storage_spec = spec.storage || {
    type: 'base'
  };
  priv.sub_storage_string = JSON.stringify(priv.sub_storage_spec);

  storage_file_object_name = 'jio/indexed_file_object/' +
    priv.sub_storage_string;

  that.serialized = function () {
    var o = super_serialized();
    o.storage = priv.sub_storage_spec;
    return o;
  };

  that.validateState = function () {
    if (!validatestate_sub_storage) {
      return 'Need at least one parameter: "storage" ' +
        'containing storage specifications.';
    }
    return '';
  };

  priv.secureDocId = function (string) {
    var split = string.split('/'),
      i;
    if (split[0] === '') {
      split = split.slice(1);
    }
    for (i = 0; i < split.length; i += 1) {
      if (split[i] === '') {
Tristan Cavelier's avatar
Tristan Cavelier committed
42
        return '';
Sven Franck's avatar
Sven Franck committed
43 44 45 46 47 48 49 50 51 52 53 54 55 56
      }
    }
    return split.join('%2F');
  };

  priv.indexStorage = function () {
    var obj = localStorage.getItem(storage_object_name) || {};
    obj[priv.sub_storage_spec] = new Date().getTime();
    localStorage.setItem(storage_object_name, obj);
  };

  priv.formatToFileObject = function (row) {
    var k, obj = {
      _id: row.id
Tristan Cavelier's avatar
Tristan Cavelier committed
57
    };
Sven Franck's avatar
Sven Franck committed
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
    for (k in row.value) {
      if (row.value.hasOwnProperty(k)) {
        obj[k] = row.value[k];
      }
    }
    return obj;
  };

  priv.allDocs = function (files_object) {
    var k, obj = {
      rows: []
    }, i = 0;
    for (k in files_object) {
      if (files_object.hasOwnProperty(k)) {
        obj.rows[i] = {};
        obj.rows[i].value = files_object[k];
        obj.rows[i].id = obj.rows[i].key = obj.rows[i].value._id;
        delete obj.rows[i].value._id;
        i += 1;
      }
    }
    obj.total_rows = obj.rows.length;
    return obj;
  };

  priv.setFileArray = function (file_array) {
    var i, obj = {};
    for (i = 0; i < file_array.length; i += 1) {
      obj[file_array[i].id] = priv.formatToFileObject(file_array[i]);
    }
    localStorage.setItem(storage_file_object_name, obj);
  };

  priv.getFileObject = function (docid) {
    var obj = localStorage.getItem(storage_file_object_name) || {};
    return obj[docid];
  };

  priv.addFile = function (file_obj) {
    var obj = localStorage.getItem(storage_file_object_name) || {};
    obj[file_obj._id] = file_obj;
    localStorage.setItem(storage_file_object_name, obj);
  };

  priv.removeFile = function (docid) {
    var obj = localStorage.getItem(storage_file_object_name) || {};
    delete obj[docid];
    localStorage.setItem(storage_file_object_name, obj);
  };

  /**
   * updates the storage.
   * It will retreive all files from a storage. It is an asynchronous task
   * so the update can be on going even if IndexedStorage has already
   * returned the result.
   * @method update
   */
  priv.update = function () {
    var success = function (val) {
      priv.setFileArray(val.rows);
Tristan Cavelier's avatar
Tristan Cavelier committed
118
    };
Sven Franck's avatar
Sven Franck committed
119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135
    that.addJob('allDocs', priv.sub_storage_spec, null, {
      max_retry: 3
    }, success, function () {});
  };

  that.post = function (command) {
    that.put(command);
  };

  /**
   * Saves a document.
   * @method put
   */
  that.put = function (command) {
    var cloned_doc = command.cloneDoc(),
      cloned_option = command.cloneOption(),
      success = function (val) {
Tristan Cavelier's avatar
Tristan Cavelier committed
136
        priv.update();
Sven Franck's avatar
Sven Franck committed
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
        that.success(val);
      },
      error = function (err) {
        that.error(err);
      };
    priv.indexStorage();
    that.addJob('put', priv.sub_storage_spec, cloned_doc,
      cloned_option, success, error);
  }; // end put

  /**
   * Loads a document.
   * @method get
   */
  that.get = function (command) {
    // jslint unused var file_array
    var success = function (val) {
        that.success(val);
      },
      error = function (err) {
        that.error(err);
      },
      get = function () {
        var cloned_option = command.cloneOption();
        that.addJob('get', priv.sub_storage_spec, command.cloneDoc(),
          cloned_option, success, error);
        that.end();
      };
    priv.indexStorage();
    priv.update();
    if (command.getOption('metadata_only')) {
      setTimeout(function () {
        var file_obj = priv.getFileObject(command.getDocId());
        if (file_obj && (file_obj._last_modified || file_obj._creation_date)) {
          that.success(file_obj);
Tristan Cavelier's avatar
Tristan Cavelier committed
172
        } else {
Sven Franck's avatar
Sven Franck committed
173
          get();
Tristan Cavelier's avatar
Tristan Cavelier committed
174
        }
Sven Franck's avatar
Sven Franck committed
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
      });
    } else {
      get();
    }
  }; // end get

  /**
   * Gets a document list.
   * @method allDocs
   */
  that.allDocs = function (command) {
    var obj = localStorage.getItem(storage_file_object_name),
      success,
      error;

    if (obj) {
      priv.update();
      setTimeout(function () {
        that.success(priv.allDocs(obj));
      });
    } else {
      success = function (val) {
        priv.setFileArray(val.rows);
        that.success(val);
      };
      error = function (err) {
        that.error(err);
      };
      that.addJob('allDocs', priv.sub_storage_spec, null,
        command.cloneOption(), success, error);
    }
  }; // end allDocs

  /**
   * Removes a document.
   * @method remove
   */
  that.remove = function (command) {
    var success = function (val) {
      priv.removeFile(command.getDocId());
      priv.update();
      that.success(val);
    },
      error = function (err) {
        that.error(err);
      };
    that.addJob('remove', priv.sub_storage_spec, command.cloneDoc(),
      command.cloneOption(), success, error);
  }; // end remove

  return that;
});