ソースを参照

Add state database `fromJSON` method.

Afshin Darian 7 年 前
コミット
2834f327f7
1 ファイル変更38 行追加0 行削除
  1. 38 0
      packages/coreutils/src/statedb.ts

+ 38 - 0
packages/coreutils/src/statedb.ts

@@ -74,6 +74,20 @@ interface IStateDB extends IDataConnector<ReadonlyJSONValue> {
    */
   fetchNamespace(namespace: string): Promise<IStateItem[]>;
 
+  /**
+   * Overwrite all the data in the state database with new contents.
+   *
+   * @param contents - The new contents of the state database.
+   *
+   * @returns A promise that resolves on success.
+   *
+   * #### Notes
+   * Each top-level key in the `contents` object will be stored as an individual
+   * value in the state database. This method accepts JSON in the same format
+   * this is returned by the `toJSON` method.
+   */
+  fromJSON(contents: ReadonlyJSONObject): Promise<void>;
+
   /**
    * Return a serialized copy of the state database's entire contents.
    *
@@ -203,6 +217,30 @@ class StateDB implements IStateDB {
     return Promise.resolve(items);
   }
 
+  /**
+   * Overwrite all the data in the state database with new contents.
+   *
+   * @param contents - The new contents of the state database.
+   *
+   * @returns A promise that resolves on success.
+   *
+   * #### Notes
+   * Each top-level key in the `contents` object will be stored as an individual
+   * value in the state database. This method accepts JSON in the same format
+   * this is returned by the `toJSON` method.
+   */
+  fromJSON(contents: ReadonlyJSONObject): Promise<void> {
+    this._clear();
+
+    try {
+      Object.keys(contents).forEach(key => { this._save(key, contents[key]); });
+    } catch (error) {
+      return Promise.reject(error);
+    }
+
+    return Promise.resolve(undefined);
+  }
+
   /**
    * Remove a value from the database.
    *