基于electron-store的最佳实践封装工具类

龙陌 / 2024-04-29 / 原文

基于之前讨论的electron-store最佳实践,以下是一个更加完善和健壮的封装示例,包含了类型处理、默认值设定、以及一些实用方法,以适应更复杂的场景:

// storeUtil.js
const Store = require('electron-store');
const app = require('electron').app;

class StoreUtil {
  constructor(configName = 'appSettings', defaults = {}, encryptionKey = null) {
    this.store = new Store({ 
      name: configName,
      encryptionKey, // 可选,提供一个密钥用于加密存储
      defaults
    });

    // 初始化默认值,确保所有默认设置已写入存储
    for (const key in defaults) {
      if (!this.store.has(key)) {
        this.set(key, defaults[key]);
      }
    }
  }

  // 设置值,支持自动处理特殊类型如Date
  set(key, value) {
    if (value instanceof Date) {
      value = value.toISOString();
    }
    return this.store.set(key, value);
  }

  // 获取值,支持类型转换和默认值
  get(key, defaultValue = null) {
    const rawValue = this.store.get(key);
    if (rawValue === undefined && defaultValue !== null) {
      return defaultValue;
    }

    try {
      if (typeof defaultValue === 'string' && defaultValue.match(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d+Z$/)) {
        return new Date(rawValue);
      }
    } catch (error) {
      console.error(`Error converting value for key ${key}:`, error);
    }

    return rawValue;
  }

  // 删除键值对
  delete(key) {
    return this.store.delete(key);
  }

  // 清空所有存储
  clear() {
    return this.store.clear();
  }

  // 检查是否存在某个键
  has(key) {
    return this.store.has(key);
  }
}

module.exports = StoreUtil;

这个封装类不仅提供了基础的读写操作,还额外处理了日期类型的序列化与反序列化,以及检查和设置默认值的功能。
此外,它还允许传入一个加密密钥(encryptionKey),以便在需要时对存储的内容进行加密处理(这要求使用支持加密的electron-store版本或其他加密插件)。
通过这样的封装,你的应用程序可以更加灵活和安全地管理持久化数据。