@silver-zepp/easy-storage
Version:
The Easy Storage library offers a suite of storage solutions designed for ZeppOS applications, providing a range of data persistence strategies to accommodate different data management needs.
3 lines (2 loc) • 1.45 kB
JavaScript
/** @about Easy Storage @min_zeppos 2.0 @author: Silver, Zepp Health. @license: MIT */
import{debugLog}from"./core/core";import{Storage}from"./storage";export class EasyStorage{#filename;#content_obj={};#autosave=true;constructor(filename="easy_storage.json"){this.#filename=filename;this.#content_obj=Storage.ReadJson(filename)}setKey(key,value){debugLog(2,`Saving key: ${key} with value: ${value}`);this.#content_obj[key]=value;if(this.#autosave)this.saveAll()}getKey(key,default_value=""){debugLog(3,`Retrieving key: ${key}`);if(Object.prototype.hasOwnProperty.call(this.#content_obj,key)){const value=this.#content_obj[key];debugLog(2,`Found value for key '${key}': ${value}`);return value}debugLog(3,`Key '${key}' not found, returning default value: ${default_value}`);return default_value===""?undefined:default_value}hasKey(key){return Object.prototype.hasOwnProperty.call(this.#content_obj,key)}removeKey(key){delete this.#content_obj[key];if(this.#autosave)this.saveAll()}saveAll(){Storage.WriteJson(this.GetStorageFilename(),this.#content_obj)}deleteAll(){this.#content_obj={};if(this.#autosave)this.saveAll()}printContents(){console.log("Storage contents: "+JSON.stringify(this.#content_obj))}getStorageSnapshot(stringify=false){return stringify?JSON.stringify(this.#content_obj):this.#content_obj}SetAutosaveEnable(bool){this.#autosave=bool}SetStorageFilename(filename){this.#filename=filename}GetStorageFilename(){return this.#filename}}