import { AppUtil } from './AppUtil';
import { distributedKVStore } from '@kit.ArkData';
import { BusinessError } from '@kit.BasicServicesKit';
/**
* 键值型数据库工具类
* @author CSDN-鸿蒙布道师
* @since 2025/04/18
*/
export class KvUtil {
private static kvStore: distributedKVStore.SingleKVStore; // KVStore数据库实例
/**
* 获取KVStore数据库实例
* @returns Promise<distributedKVStore.SingleKVStore>
*/
private static async getKvStore(): Promise<distributedKVStore.SingleKVStore> {
if (!KvUtil.kvStore) {
const kvManager = distributedKVStore.createKVManager({
context: AppUtil.getContext(),
bundleName: AppUtil.getBundleName(),
});
const options: distributedKVStore.Options = {
createIfMissing: true, // 数据库不存在时是否创建
encrypt: true, // 是否加密数据库
backup: false, // 是否支持备份
autoSync: false, // 是否跨设备自动同步
kvStoreType: distributedKVStore.KVStoreType.SINGLE_VERSION, // 数据库类型
securityLevel: distributedKVStore.SecurityLevel.S1, // 数据库安全级别
};
KvUtil.kvStore = await kvManager.getKVStore('harmony_utils_store', options);
}
return KvUtil.kvStore;
}
/**
* 添加指定类型的键值对到数据库
* @param key 键
* @param value 值(支持 Uint8Array | string | number | boolean)
*/
static async put(key: string, value: Uint8Array | string | number | boolean): Promise<void> {
const kvStore = await KvUtil.getKvStore();
await kvStore.put(key, value);
}
/**
* 获取指定键的值,支持默认值
* @param key 键
* @param defValue 默认值
* @returns Promise<T | undefined>
*/
private static async getValue<T>(key: string, defValue?: T): Promise<T | undefined> {
const kvStore = await KvUtil.getKvStore();
try {
const value = await kvStore.get(key);
// 使用类型断言确保返回值符合 T 类型
return (value !== undefined && value !== null ? value as T : defValue);
} catch (error) {
console.error(`KvUtil-getValue Error: ${error}`);
return defValue;
}
}
/**
* 获取字符串类型的值
* @param key 键
* @param defValue 默认值
*/
static async getString(key: string, defValue = ''): Promise<string> {
return (await KvUtil.getValue<string>(key, defValue)) ?? '';
}
/**
* 获取数字类型的值
* @param key 键
* @param defValue 默认值
*/
static async getNumber(key: string, defValue = 0): Promise<number> {
return (await KvUtil.getValue<number>(key, defValue)) ?? 0;
}
/**
* 获取布尔类型的值
* @param key 键
* @param defValue 默认值
*/
static async getBoolean(key: string, defValue = false): Promise<boolean> {
return (await KvUtil.getValue<boolean>(key, defValue)) ?? false;
}
/**
* 获取 Uint8Array 类型的值
* @param key 键
* @param defValue 默认值
*/
static async getUint8Array(key: string, defValue: Uint8Array = new Uint8Array()): Promise<Uint8Array> {
return (await KvUtil.getValue<Uint8Array>(key, defValue)) ?? new Uint8Array();
}
/**
* 删除指定键的值
* @param key 键
*/
static async delete(key: string): Promise<void> {
const kvStore = await KvUtil.getKvStore();
await kvStore.delete(key);
}
/**
* 批量插入键值对
* @param entries 键值对数组
*/
static async putBatch(entries: distributedKVStore.Entry[]): Promise<void> {
const kvStore = await KvUtil.getKvStore();
await kvStore.putBatch(entries);
}
/**
* 批量删除键值对
* @param keys 键数组
*/
static async deleteBatch(keys: string[]): Promise<void> {
const kvStore = await KvUtil.getKvStore();
await kvStore.deleteBatch(keys);
}
/**
* 获取匹配指定键前缀的所有键值对
* @param keyPrefix 键前缀
*/
static async getEntries(keyPrefix: string): Promise<distributedKVStore.Entry[]> {
const kvStore = await KvUtil.getKvStore();
return kvStore.getEntries(keyPrefix);
}
/**
* 备份数据库
* @param file 备份文件名
*/
static async backup(file: string): Promise<void> {
const kvStore = await KvUtil.getKvStore();
await kvStore.backup(file);
}
/**
* 恢复数据库
* @param file 备份文件名
*/
static async restore(file: string): Promise<void> {
const kvStore = await KvUtil.getKvStore();
await kvStore.restore(file);
}
/**
* 删除备份文件
* @param files 备份文件名数组
*/
static async deleteBackup(files: string[]): Promise<Array<[string, number]>> {
const kvStore = await KvUtil.getKvStore();
return kvStore.deleteBackup(files);
}
/**
* 订阅数据变更通知
* @param type 订阅类型
* @param listener 回调函数
*/
static async onDataChange(
type: distributedKVStore.SubscribeType,
listener: Callback<distributedKVStore.ChangeNotification>
): Promise<void> {
const kvStore = await KvUtil.getKvStore();
kvStore.on('dataChange', type, listener);
}
/**
* 取消订阅数据变更通知
* @param listener 回调函数(不传则取消所有订阅)
*/
static async offDataChange(listener?: Callback<distributedKVStore.ChangeNotification>): Promise<void> {
const kvStore = await KvUtil.getKvStore();
if (listener) {
kvStore.off('dataChange', listener);
} else {
kvStore.off('dataChange');
}
}
}
代码如下:
import { AppUtil } from './AppUtil';
import { distributedKVStore } from '@kit.ArkData';
import { BusinessError } from '@kit.BasicServicesKit';
/**
* 键值型数据库工具类
* @author CSDN-鸿蒙布道师
* @since 2025/04/18
*/
export class KvUtil {
private static kvStore: distributedKVStore.SingleKVStore; // KVStore数据库实例
/**
* 获取KVStore数据库实例
* @returns Promise<distributedKVStore.SingleKVStore>
*/
private static async getKvStore(): Promise<distributedKVStore.SingleKVStore> {
if (!KvUtil.kvStore) {
const kvManager = distributedKVStore.createKVManager({
context: AppUtil.getContext(),
bundleName: AppUtil.getBundleName(),
});
const options: distributedKVStore.Options = {
createIfMissing: true, // 数据库不存在时是否创建
encrypt: true, // 是否加密数据库
backup: false, // 是否支持备份
autoSync: false, // 是否跨设备自动同步
kvStoreType: distributedKVStore.KVStoreType.SINGLE_VERSION, // 数据库类型
securityLevel: distributedKVStore.SecurityLevel.S1, // 数据库安全级别
};
KvUtil.kvStore = await kvManager.getKVStore('harmony_utils_store', options);
}
return KvUtil.kvStore;
}
/**
* 添加指定类型的键值对到数据库
* @param key 键
* @param value 值(支持 Uint8Array | string | number | boolean)
*/
static async put(key: string, value: Uint8Array | string | number | boolean): Promise<void> {
const kvStore = await KvUtil.getKvStore();
await kvStore.put(key, value);
}
/**
* 获取指定键的值,支持默认值
* @param key 键
* @param defValue 默认值
* @returns Promise<T | undefined>
*/
private static async getValue<T>(key: string, defValue?: T): Promise<T | undefined> {
const kvStore = await KvUtil.getKvStore();
try {
const value = await kvStore.get(key);
// 使用类型断言确保返回值符合 T 类型
return (value !== undefined && value !== null ? value as T : defValue);
} catch (error) {
console.error(`KvUtil-getValue Error: ${error}`);
return defValue;
}
}
/**
* 获取字符串类型的值
* @param key 键
* @param defValue 默认值
*/
static async getString(key: string, defValue = ''): Promise<string> {
return (await KvUtil.getValue<string>(key, defValue)) ?? '';
}
/**
* 获取数字类型的值
* @param key 键
* @param defValue 默认值
*/
static async getNumber(key: string, defValue = 0): Promise<number> {
return (await KvUtil.getValue<number>(key, defValue)) ?? 0;
}
/**
* 获取布尔类型的值
* @param key 键
* @param defValue 默认值
*/
static async getBoolean(key: string, defValue = false): Promise<boolean> {
return (await KvUtil.getValue<boolean>(key, defValue)) ?? false;
}
/**
* 获取 Uint8Array 类型的值
* @param key 键
* @param defValue 默认值
*/
static async getUint8Array(key: string, defValue: Uint8Array = new Uint8Array()): Promise<Uint8Array> {
return (await KvUtil.getValue<Uint8Array>(key, defValue)) ?? new Uint8Array();
}
/**
* 删除指定键的值
* @param key 键
*/
static async delete(key: string): Promise<void> {
const kvStore = await KvUtil.getKvStore();
await kvStore.delete(key);
}
/**
* 批量插入键值对
* @param entries 键值对数组
*/
static async putBatch(entries: distributedKVStore.Entry[]): Promise<void> {
const kvStore = await KvUtil.getKvStore();
await kvStore.putBatch(entries);
}
/**
* 批量删除键值对
* @param keys 键数组
*/
static async deleteBatch(keys: string[]): Promise<void> {
const kvStore = await KvUtil.getKvStore();
await kvStore.deleteBatch(keys);
}
/**
* 获取匹配指定键前缀的所有键值对
* @param keyPrefix 键前缀
*/
static async getEntries(keyPrefix: string): Promise<distributedKVStore.Entry[]> {
const kvStore = await KvUtil.getKvStore();
return kvStore.getEntries(keyPrefix);
}
/**
* 备份数据库
* @param file 备份文件名
*/
static async backup(file: string): Promise<void> {
const kvStore = await KvUtil.getKvStore();
await kvStore.backup(file);
}
/**
* 恢复数据库
* @param file 备份文件名
*/
static async restore(file: string): Promise<void> {
const kvStore = await KvUtil.getKvStore();
await kvStore.restore(file);
}
/**
* 删除备份文件
* @param files 备份文件名数组
*/
static async deleteBackup(files: string[]): Promise<Array<[string, number]>> {
const kvStore = await KvUtil.getKvStore();
return kvStore.deleteBackup(files);
}
/**
* 订阅数据变更通知
* @param type 订阅类型
* @param listener 回调函数
*/
static async onDataChange(
type: distributedKVStore.SubscribeType,
listener: Callback<distributedKVStore.ChangeNotification>
): Promise<void> {
const kvStore = await KvUtil.getKvStore();
kvStore.on('dataChange', type, listener);
}
/**
* 取消订阅数据变更通知
* @param listener 回调函数(不传则取消所有订阅)
*/
static async offDataChange(listener?: Callback<distributedKVStore.ChangeNotification>): Promise<void> {
const kvStore = await KvUtil.getKvStore();
if (listener) {
kvStore.off('dataChange', listener);
} else {
kvStore.off('dataChange');
}
}
}



















