storage.uts 9.36 KB
// 过期时间后缀,用于标识存储数据的过期时间键名
const EXPIRES_SUFFIX = "_deadtime";

/**
 * 存储管理类
 *
 * 封装了 uni-app 的存储 API,提供更便捷的存储操作
 * 支持数据过期时间管理,自动处理过期数据
 */
class Storage {
	/**
	 * 清空所有存储数据
	 *
	 * 警告:此操作会删除所有本地存储数据,请谨慎使用
	 *
	 * @example
	 * storage.clear(); // 清空所有数据
	 */
	clear() {
		uni.clearStorageSync();
	}

	/**
	 * 获取存储的原始数据
	 *
	 * @param key 存储键名
	 * @returns 存储的原始数据,不做任何处理
	 *
	 * @example
	 * const rawData = storage.getRaw('user');
	 */
	get(key: string): any | null {
		return uni.getStorageSync(key);
	}

	/**
	 * 读取缓存的车品牌列表(键名仅在 .uts 中字面量,避免 uvue 调用 get 时 Android kotlin/java String 桥接报错)
	 */
	getCarBrandList(): any | null {
		return this.get("carBrandList");
	}

	/**
	 * 读取缓存的用户信息(同上,规避 uvue 字符串字面量传入 get 的编译问题)
	 *
	 * ✅ 自动处理 JSON 字符串解析,支持 string 和 object 两种格式
	 *
	 * @returns UTSJSONObject 对象,如果获取失败则返回空对象
	 *
	 * @example
	 * const userInfo = storage.getUserInfo();
	 * const userName = userInfo.get('userName');
	 */
	getUserInfo(): UTSJSONObject {
		const storedUserInfo = this.get("userInfo");
		return this._parseData(storedUserInfo);
	}

	/**
	 * 写入车品牌列表缓存(键名字面量仅在 .uts,规避 uvue 调 set 的 Android 字符串桥接问题)
	 */
	setCarBrandList(value: any): void {
		this.set("carBrandList", value, 0);
	}

	/**
	 * 获取存储数据并自动解析为 UTSJSONObject
	 *
	 * 从 storage 中获取指定 key 的数据,如果是字符串会自动解析为 JSON
	 * 支持 string 和 object 两种数据格式
	 *
	 * @param key 存储键名
	 * @returns 解析后的 UTSJSONObject 对象,如果获取失败则返回空对象
	 *
	 * @example
	 * // 获取用户信息
	 * const userInfo = storage.get('userInfo');
	 * const loginPhone = userInfo.get('loginPhone');
	 *
	 * @example
	 * // 获取配置数据
	 * const config = storage.get('config');
	 * const value = config.get('someKey');
	 */
	getParse(key: string): UTSJSONObject {
		const data = uni.getStorageSync(key);
		return this._parseData(data);
	}

	/**
	 * 获取所有存储数据的信息
	 *
	 * 遍历所有存储键,返回包含所有键值对的对象
	 * 注意:此方法会读取所有存储数据,大量数据时需注意性能
	 *
	 * @returns 包含所有存储数据的对象
	 *
	 * @example
	 * const allData = storage.info();
	 * console.log('所有存储数据:', allData);
	 */
	info() {
		// 获取存储信息,包含所有键名
		const info = uni.getStorageInfoSync();

		// 创建空对象用于存放所有数据
		const d = {};

		// 遍历所有键名,获取对应的值
		info.keys.forEach((e) => {
			d[e] = this.get(e);
		});

		return d;
	}

	/**
	 * 检查数据是否已过期
	 *
	 * @param key 存储键名
	 * @returns true表示已过期或无过期时间设置,false表示未过期
	 *
	 * @example
	 * if (storage.isExpired('token')) {
	 *   console.log('token已过期');
	 * }
	 */
	isExpired(key: string): boolean {
		// 获取过期时间戳
		const value = uni.getStorageSync(`${key}${EXPIRES_SUFFIX}`) as null | number;

		// 如果没有设置过期时间,视为已过期
		if (value == null) {
			return true;
		}

		// 比较过期时间戳与当前时间,判断是否过期
		return value - Date.now() <= 0;
	}

	/**
	 * 获取数据后立即删除(一次性读取)
	 *
	 * 适用于临时数据、一次性令牌等场景
	 * 读取后数据会被自动删除,确保数据的一次性使用
	 *
	 * @param key 存储键名
	 * @returns 存储的数据,如果不存在则返回 null
	 *
	 * @example
	 * const tempToken = storage.once('temp_token');
	 * // tempToken 使用后,存储中的 temp_token 已被删除
	 */
	once(key: string): any | null {
		// 先获取数据
		const value = this.get(key);
		// 立即删除数据
		this.remove(key);
		// 返回获取到的数据
		return value;
	}

	/**
	 * 解析存储的数据为 UTSJSONObject
	 *
	 * 从 storage 中获取指定 key 的数据并解析为 UTSJSONObject 对象
	 * 支持 string 和 object 两种数据格式,自动处理 JSON 解析
	 *
	 * @param key 存储键名
	 * @returns 解析后的 UTSJSONObject 对象,如果获取失败则返回空对象
	 *
	 * @example
	 * // 解析用户信息
	 * const userInfo = storage.parse('userInfo');
	 * const loginPhone = userInfo.get('loginPhone');
	 *
	 * @example
	 * // 解析其他任意数据
	 * const config = storage.parse('config');
	 * const value = config.get('someKey');
	 */
	parse(key: string): UTSJSONObject {
		const data = this.get(key);
		return this._parseData(data);
	}

	/**
	 * 删除存储数据
	 *
	 * 会同时删除数据本身和对应的过期时间
	 *
	 * @param key 存储键名
	 *
	 * @example
	 * storage.remove('user');
	 * storage.remove('token');
	 */
	remove(key: string) {
		// 删除主要数据
		uni.removeStorageSync(key);
		// 删除对应的过期时间数据
		uni.removeStorageSync(`${key}${EXPIRES_SUFFIX}`);
	}

	/**
	 * ✅ 性能优化:异步删除存储数据,避免阻塞主线程
	 *
	 * 使用 uni.removeStorage 异步 API,将删除操作放入后台执行
	 * 适用于非关键路径的删除操作(如清理缓存、临时数据等)
	 *
	 * @param key 存储键名
	 *
	 * @example
	 * // 异步删除,不阻塞主线程
	 * storage.removeAsync('cache_data');
	 * storage.removeAsync('temp_logs');
	 */
	removeAsync(key: string): void {
		// 删除主要数据
		uni.removeStorage({
			key: key,
			success: () => {
				// #ifdef DEBUG
				console.log(`[storage.removeAsync] 成功 - key: ${key}`);
				// #endif
			},
			fail: (err) => {
				console.error(`[storage.removeAsync] 失败 - key: ${key}`, err);
			}
		});

		// 删除对应的过期时间数据
		uni.removeStorage({
			key: `${key}${EXPIRES_SUFFIX}`,
			success: () => {
				// #ifdef DEBUG
				console.log(`[storage.removeAsync] 成功 - key: ${key}${EXPIRES_SUFFIX}`);
				// #endif
			},
			fail: (err) => {
				// 过期时间不存在时忽略错误
			}
		});
	}

	/**
	 * 设置存储数据
	 *
	 * @param key 存储键名
	 * @param value 要存储的数据,支持任意类型
	 * @param expires 过期时间(秒),默认为0表示永不过期
	 *
	 * @example
	 * // 存储永久数据
	 * storage.set('user', { name: '张三', age: 25 }, 0);
	 *
	 * // 存储5分钟后过期的数据
	 * storage.set('token', 'abc123', 300);
	 */
	set(key: string, value: any, expires: number): void {
		// 对于数组或复杂对象,先序列化为 JSON 字符串再存储,确保数据完整性
		let storageValue: any = value;
		if (value != null && typeof value === "object") {
			try {
				// 使用 JSON 字符串存储,确保 iOS 兼容性
				const jsonStr = JSON.stringify(value);
				storageValue = jsonStr;
			} catch (e) {
				console.error(`[storage.set] 序列化失败 - key: ${key}`, e);
				// 序列化失败时使用原始值
				storageValue = value;
			}
		}

		// 存储主要数据
		uni.setStorageSync(key, storageValue);

		// 如果设置了过期时间,则存储过期时间戳
		if (expires > 0) {
			// 计算过期时间戳:当前时间 + 过期时间(秒转毫秒)
			const expireTime = Date.now() + expires * 1000;
			uni.setStorageSync(`${key}${EXPIRES_SUFFIX}`, expireTime);
		}
	}

	/**
	 * ✅ 性能优化:异步设置存储数据,避免阻塞主线程
	 *
	 * 使用 uni.setStorage 异步 API,将存储操作放入后台执行
	 * 适用于非关键路径的存储操作(如日志、缓存等)
	 *
	 * @param key 存储键名
	 * @param value 要存储的数据,支持任意类型
	 * @param expires 过期时间(秒),默认为0表示永不过期(注意:异步存储不支持过期时间)
	 *
	 * @example
	 * // 异步存储,不阻塞主线程
	 * storage.setAsync('cache_data', data);
	 * storage.setAsync('logs', logs);
	 */
	setAsync(key: string, value: any, expires: number = 0): void {
		// 对于数组或复杂对象,先序列化为 JSON 字符串再存储
		let storageValue: any = value;
		if (value != null && typeof value === "object") {
			try {
				const jsonStr = JSON.stringify(value);
				storageValue = jsonStr;
			} catch (e) {
				console.error(`[storage.setAsync] 序列化失败 - key: ${key}`, e);
				storageValue = value;
			}
		}

		// 使用 uni.setStorage 异步 API
		uni.setStorage({
			key: key,
			data: storageValue,
			success: () => {
				// #ifdef DEBUG
				console.log(`[storage.setAsync] 成功 - key: ${key}`);
				// #endif
			},
			fail: (err) => {
				console.error(`[storage.setAsync] 失败 - key: ${key}`, err);
			}
		});
	}

	/**
	 * 解析数据的内部辅助方法
	 *
	 * @param data 要解析的数据
	 * @returns 解析后的 UTSJSONObject 对象
	 */
	private _parseData(data: any | null): UTSJSONObject {
		let obj: UTSJSONObject = {};

		// 支持 string 和 object 两种类型
		if (typeof data === "string" && data !== "") {
			try {
				obj = JSON.parse(data) as UTSJSONObject;
			} catch (error) {
				console.warn(`Failed to parse JSON: ${error}`);
			}
		} else if (data !== null && typeof data === "object") {
			obj = data as UTSJSONObject;
		}

		return obj;
	}
}

// 导出存储实例,提供全局访问
export const storage = new Storage();