提交 2fcc6a0b 编写于 作者: DCloud-yyl's avatar DCloud-yyl

开源:storage本地数据存储相关API

上级 4b595d93
{
"id": "UTS-Storage",
"displayName": "UTS-Storage",
"version": "1.0.0",
"description": "UTS-Storage",
"keywords": [
"UTS-Storage"
],
"repository": "",
"engines": {
"HBuilderX": "^3.6.8"
},
"dcloudext": {
"type": "uts",
"sale": {
"regular": {
"price": "0.00"
},
"sourcecode": {
"price": "0.00"
}
},
"contact": {
"qq": ""
},
"declaration": {
"ads": "",
"data": "",
"permissions": ""
},
"npmurl": ""
},
"uni_modules": {
"uni-ext-api": {
"uni": {
"setStorage": {
"name": "setStorage",
"app": {
"js": false,
"kotlin": true,
"swift": true
}
},
"setStorageSync": {
"name": "setStorageSync",
"app": {
"js": false,
"kotlin": true,
"swift": true
}
},
"getStorage": {
"name": "getStorage",
"app": {
"js": false,
"kotlin": true,
"swift": true
}
},
"getStorageSync": {
"name": "getStorageSync",
"app": {
"js": false,
"kotlin": true,
"swift": true
}
},
"getStorageInfo": {
"name": "getStorageInfo",
"app": {
"js": false,
"kotlin": true,
"swift": true
}
},
"getStorageInfoSync": {
"name": "getStorageInfoSync",
"app": {
"js": false,
"kotlin": true,
"swift": true
}
},
"removeStorage": {
"name": "removeStorage",
"app": {
"js": false,
"kotlin": true,
"swift": true
}
},
"removeStorageSync": {
"name": "removeStorageSync",
"app": {
"js": false,
"kotlin": true,
"swift": true
}
},
"clearStorage": {
"name": "clearStorage",
"app": {
"js": false,
"kotlin": true,
"swift": true
}
},
"clearStorageSync": {
"name": "clearStorageSync",
"app": {
"js": false,
"kotlin": true,
"swift": true
}
}
}
},
"dependencies": [],
"encrypt": [],
"platforms": {
"cloud": {
"tcb": "u",
"aliyun": "u"
},
"client": {
"Vue": {
"vue2": "u",
"vue3": "u"
},
"App": {
"app-android": "u",
"app-ios": "u"
},
"H5-mobile": {
"Safari": "u",
"Android Browser": "u",
"微信浏览器(Android)": "u",
"QQ浏览器(Android)": "u"
},
"H5-pc": {
"Chrome": "u",
"IE": "u",
"Edge": "u",
"Firefox": "u",
"Safari": "u"
},
"小程序": {
"微信": "u",
"阿里": "u",
"百度": "u",
"字节跳动": "u",
"QQ": "u",
"钉钉": "u",
"快手": "u",
"飞书": "u",
"京东": "u"
},
"快应用": {
"华为": "u",
"联盟": "u"
}
}
}
}
}
\ No newline at end of file
# UTS-Storage
### 开发文档
[UTS 语法](https://uniapp.dcloud.net.cn/tutorial/syntax-uts.html)
[UTS API插件](https://uniapp.dcloud.net.cn/plugin/uts-plugin.html)
[UTS 组件插件](https://uniapp.dcloud.net.cn/plugin/uts-component.html)
[Hello UTS](https://gitcode.net/dcloud/hello-uts)
\ No newline at end of file
import { SetStorage, SetStorageOptions, SetStorageSuccess } from "../interface.uts"
import { SetStorageSync } from "../interface.uts"
import { GetStorage, GetStorageOptions, GetStorageSuccess } from "../interface.uts"
import { GetStorageSync } from "../interface.uts"
import { GetStorageInfoSuccess, GetStorageInfo, GetStorageInfoOptions } from "../interface.uts"
import { GetStorageInfoSync } from "../interface.uts"
import { RemoveStorage, RemoveStorageOptions, RemoveStorageSuccess } from "../interface.uts"
import { RemoveStorageSync } from "../interface.uts"
import { ClearStorage, ClearStorageSuccess, ClearStorageOptions } from "../interface.uts"
import { ClearStorageSync } from "../interface.uts"
// @ts-expect-error
import DCStorage from "io.dcloud.common.util.db.DCStorage";
// @ts-expect-error
import UTSAndroid from 'io.dcloud.uts.UTSAndroid';
// @ts-expect-error
import List from 'java.util.List';
import {
uni_getStorageAsync,
uni_getStorageSync,
uni_setStorageAsync,
uni_setStorageSync
} from "../uniStorageTool.uts"
/**
* 设置储存项
*/
export const setStorage: SetStorage = function (options: SetStorageOptions) {
setTimeout(function () {
let dcStorage = DCStorage.getDCStorage(UTSAndroid.getUniActivity());
if (dcStorage == null) {
let ret = new UniError("uni-setStorage", -1, "storage not found.")
options.fail?.(ret)
options.complete?.(ret)
return
}
/**
* 通过公共函数执行设置逻辑
*/
uni_setStorageAsync(options, (itemKey: string, itemData: string) => {
dcStorage.performSetItem(UTSAndroid.getUniActivity(), UTSAndroid.getAppId(), itemKey, itemData);
}, (itemKey: string) => {
dcStorage.performRemoveItem(UTSAndroid.getUniActivity(), UTSAndroid.getAppId(), itemKey);
})
}, 0)
}
/**
* 同步设置储存项
*/
export const setStorageSync: SetStorageSync = function (key: string, data: any) {
let dcStorage = DCStorage.getDCStorage(UTSAndroid.getUniActivity());
if (dcStorage == null) {
// 异常了
return;
}
uni_setStorageSync(key, data, (itemKey: string, itemValue: string) => {
let dataString = itemValue
if (typeof data == "string") {
// string 类型不进行序列化
dataString = data as string
}
dcStorage.performSetItem(UTSAndroid.getUniActivity(), UTSAndroid.getAppId(), itemKey, dataString);
}, (itemKey: string) => {
dcStorage.performRemoveItem(UTSAndroid.getUniActivity(), UTSAndroid.getAppId(), itemKey);
})
}
/**
* 获取储存项
*/
function includeKey(key: string): boolean {
let info = DCStorage.getDCStorage(UTSAndroid.getUniActivity()!).performGetAllKeys(UTSAndroid.getAppId())
console.log(info)
if (info.v != null && info.code == DCStorage.SUCCESS) {
//&& info.v instanceof java.util.List
// @ts-expect-error
let keys = UTSArray.fromNative((info.v as ArrayList<String>));
if (keys.indexOf(key) > -1) {
return true
}
}
return false;
}
export const getStorage: GetStorage = function getStorage(options: GetStorageOptions) {
let dcStorage = DCStorage.getDCStorage(UTSAndroid.getUniActivity());
if (dcStorage == null) {
let ret = new UniError("uni-setStorage", -1, "storage not found.")
options.fail?.(ret)
options.complete?.(ret)
return
}
setTimeout(function () {
uni_getStorageAsync(options, function (itemKey: string): string | null {
let info = dcStorage.performGetItem(UTSAndroid.getAppId(), itemKey);
if (info != null && info.code == DCStorage.SUCCESS && info.v != null) {
// 获取成功
return info.v as string
}
return null
}, function (key: string): boolean {
let list: String[] = []
let info = dcStorage.performGetAllKeys(UTSAndroid.getAppId())
if (info.code == DCStorage.SUCCESS && info.v != null) {
/**
* 临时语法支持,foreach 组织数组格式
*/
let arrayKeys: String[] = []
;(info.v as List<string>).forEach((perKey: string) => {
arrayKeys.push(perKey)
});
list = arrayKeys
}
if (list != null) {
let item = list!.find((value): boolean => {
if (typeof value == "string") {
return (value as string) == key;
}
return false;
})
return (item != null);
}
return false;
})
}, 0)
}
/**
* 同步获取储存项
*/
export const getStorageSync: GetStorageSync = function (key: string): any | null {
return uni_getStorageSync(key, function (itemKey: string): string | null {
let dcStorage = DCStorage.getDCStorage(UTSAndroid.getUniActivity());
if (dcStorage == null) {
return "";
}
let info = dcStorage.performGetItem(UTSAndroid.getAppId(), itemKey);
if (info != null && info.code == DCStorage.SUCCESS && info.v != null) {
// 获取成功
return info.v as string
}
return ""
});
}
/**
* 获取储存信息
*/
export const getStorageInfo: GetStorageInfo = function (options: GetStorageInfoOptions) {
setTimeout(function () {
let dcStorage = DCStorage.getDCStorage(UTSAndroid.getUniActivity());
if (dcStorage == null) {
let ret = new UniError("uni-setStorage", -1, "storage not found.")
options.fail?.(ret)
options.complete?.(ret)
}
let ret: GetStorageInfoSuccess = {
keys: [],
currentSize: 0,
limitSize: 10240
}
let info = dcStorage.performGetAllKeys(UTSAndroid.getAppId());
if (info.code == DCStorage.SUCCESS && info.v != null) {
let arrayKeys: string[] = []
/**
* 临时语法支持,foreach 组织数组格式
*/
;(info.v as List<string>).forEach((perKey: string) => {
arrayKeys.push(perKey)
});
/**
* 储存的最大值:SQLLite数据库当前允许的最大值
* 储存的已用值:SQLLite数据文件当前的大小
*/
try {
ret.keys = arrayKeys
let limitNum = dcStorage.getDBMaxLength(UTSAndroid.getAppId()).toDouble()
ret.limitSize = limitNum / 1024
let currentNum = dcStorage.getDBCurrentLength(UTSAndroid.getAppId()).toDouble()
ret.currentSize = currentNum / 1024
} catch (e) {
//TODO handle the exception
}
// let arrayRet = info.v as Array
options.success?.(ret)
}
}, 0)
}
/**
* 同步获取储存信息
*/
export const getStorageInfoSync: GetStorageInfoSync = function (): GetStorageInfoSuccess {
// android SQL 单表最大限制为
let ret: GetStorageInfoSuccess = {
keys: [],
currentSize: 0,
limitSize: 10240,
}
let dcStorage = DCStorage.getDCStorage(UTSAndroid.getUniActivity());
if (dcStorage == null) {
return ret
}
let info = dcStorage.performGetAllKeys(UTSAndroid.getAppId());
if (info.code == DCStorage.SUCCESS && info.v != null) {
/**
* 临时语法支持,foreach 组织数组格式
*/
let arrayKeys: string[] = []
;(info.v as List<string>).forEach((perKey: string) => {
arrayKeys.push(perKey)
});
ret.keys = arrayKeys
}
/**
* 储存的最大值:SQLLite数据库当前允许的最大值
* 储存的已用值:SQLLite数据文件当前的大小
*/
try {
let limitNum = dcStorage.getDBMaxLength(UTSAndroid.getAppId()).toDouble()
ret.limitSize = limitNum / 1024
let currentNum = dcStorage.getDBCurrentLength(UTSAndroid.getAppId()).toDouble()
ret.currentSize = currentNum / 1024
} catch (e) {
//TODO handle the exception
}
return ret
}
/**
* 移除指定储存项
*/
export const removeStorage: RemoveStorage = function (options: RemoveStorageOptions) {
setTimeout(function () {
let dcStorage = DCStorage.getDCStorage(UTSAndroid.getUniActivity());
if (dcStorage == null) {
let ret = new UniError("uni-removeStorage", -1, "storage not found.")
options.fail?.(ret)
options.complete?.(ret)
return;
}
dcStorage.performRemoveItem(UTSAndroid.getUniActivity(), UTSAndroid.getAppId(), options.key);
let ret: RemoveStorageSuccess = {}
options.success?.(ret)
options.complete?.(ret)
}, 0)
}
/**
* 同步移除指定储存项
*/
export const removeStorageSync: RemoveStorageSync = function (key: string) {
let dcStorage = DCStorage.getDCStorage(UTSAndroid.getUniActivity());
if (dcStorage == null) {
return;
}
dcStorage.performRemoveItem(UTSAndroid.getUniActivity(), UTSAndroid.getAppId(), key);
}
/**
* 清空储存选项
*/
export const clearStorage: ClearStorage = function (option: ClearStorageOptions | null) {
setTimeout(function () {
let dcStorage = DCStorage.getDCStorage(UTSAndroid.getUniActivity());
if (dcStorage == null) {
let ret = new UniError("uni-clearStorage", -1, "error:storage not found.")
option?.fail?.(ret)
option?.complete?.(ret)
return;
}
dcStorage.performClear(UTSAndroid.getUniActivity(), UTSAndroid.getAppId());
let ret: ClearStorageSuccess = {}
option?.success?.(ret)
option?.complete?.(ret)
}, 0)
}
/**
* 同步清空储存选项
*/
export const clearStorageSync: ClearStorageSync = function () {
let dcStorage = DCStorage.getDCStorage(UTSAndroid.getUniActivity());
if (dcStorage == null) {
return;
}
dcStorage.performClear(UTSAndroid.getUniActivity(), UTSAndroid.getAppId());
}
//
// StorageManager.h
// storage
//
// Created by DCloud on 2018/6/13.
// Copyright © 2018年 DCloud. All rights reserved.
//
#import <Foundation/Foundation.h>
typedef void (^StorageManagerCallback)(id result);
@class Storage;
@interface StorageManager : NSObject
+ (Storage*)currentStorage;
+ (Storage*)activeStorageWithDomain:(NSString*)domain;
+ (void)serializeStorageWithDomain:(NSString*)domain;
+ (Storage*)storageWithDomain:(NSString*)domain;
@end
@interface Storage : NSObject
@property(nonatomic, strong)NSString* domain;
@property(nonatomic, strong)NSString* rootPath;
- (NSUInteger)length;
- (NSArray*)getAllKeys;
- (void)setItem:(NSString *)key value:(NSString *)value callback:(StorageManagerCallback)callback;
- (void)setItemPersistent:(NSString *)key value:(NSString *)value callback:(StorageManagerCallback)callback;
- (NSString*)getItem:(NSString *)key callback:(StorageManagerCallback)callback;
- (void)removeItem:(NSString *)key callback:(StorageManagerCallback)callback;
- (void)clear;
@end
//
// storage.h
// storage
//
// Created by DCloud on 2018/6/13.
// Copyright © 2018年 DCloud. All rights reserved.
//
#import <UIKit/UIKit.h>
//! Project version number for storage.
FOUNDATION_EXPORT double storageVersionNumber;
//! Project version string for storage.
FOUNDATION_EXPORT const unsigned char storageVersionString[];
// In this header, you should import all the public headers of your framework using statements like #import <storage/PublicHeader.h>
#import <storage/StorageManager.h>
framework module storage {
umbrella header "storage.h"
export *
module * { export * }
}
import { SetStorageSuccess, SetStorageOptions, SetStorage, SetStorageSync, GetStorageSuccess, GetStorageOptions, GetStorage, GetStorageSync, GetStorageInfoSuccess, GetStorageInfoOptions, GetStorageInfo, GetStorageInfoSync, RemoveStorageSuccess, RemoveStorageOptions, RemoveStorage, RemoveStorageSync, ClearStorage, ClearStorageSync, ClearStorageOptions, ClearStorageSuccess} from "../interface.uts"
import { Storage, StorageManager } from "storage" assert { type: "implementationOnly" };
import { UTSiOS, dc_storage_aes_key, dc_storage_path_component, dc_storage_old_path_component } from "DCloudUTSFoundation";
import { NSDictionary, URL, FileManager, PropertyListSerialization, NSData, NSKeyedUnarchiver } from 'Foundation';
import { uni_getStorageAsync, uni_getStorageSync, uni_setStorageAsync, uni_setStorageSync } from "../uniStorageTool.uts"
class StorageTool {
protected static storage: Storage | null
private static migrateStorage(storage: Storage) {
let dataPath = UTSiOS.getDataPath()
const oldPath = new URL(fileURLWithPath = dataPath).appendingPathComponent(dc_storage_old_path_component).absoluteString
let content: any | null = null
if (FileManager.default.fileExists(atPath = oldPath)) {
let data = FileManager.default.contents(atPath = oldPath)
if (data != null) {
content = PropertyListSerialization.propertyListFromData(data!, mutabilityOption = [PropertyListSerialization.MutabilityOptions.mutableContainersAndLeaves], format = null, errorDescription = null)
}
try {
UTSiOS.try(FileManager.default.removeItem(atPath = oldPath))
} catch (e) {
// console.log(e)
}
} else{
const path = new URL(fileURLWithPath = dataPath).appendingPathComponent(dc_storage_path_component).absoluteString
let inputData = NSData.init(contentsOfFile = path)
if ( inputData != null ) {
let data = UTSiOS.dc_AESDecrypt(data = inputData!, key = dc_storage_aes_key)
if (data != null) {
content = NSKeyedUnarchiver.unarchiveObject(with = data!)
}
}
try {
UTSiOS.try(FileManager.default.removeItem(atPath = path))
} catch (e) {
// console.log(e)
}
}
if (content != null ) {
let contentDic = UTSiOS.convertDictionary(content!)
if (contentDic.isEmpty == false) {
let dic = new NSDictionary(dictionary = contentDic)
let i = 0
while (i < dic.allKeys.length){
let key = dic.allKeys[i]
if (key != null && typeof key == "string") {
let value = dic.value(forKey = key as string)
if (value != null && typeof value == "string") {
storage.setItem(key as string, value = value as string, callback = null)
}
}
i++
}
}
}
}
protected static getStorage(): Storage {
if (this.storage != null) {
return this.storage!
}
const domain: string = UTSiOS.getAppId()
let storage: Storage | null = null
storage = StorageManager.storage(withDomain = domain)
if (this.storage == null) {
storage = StorageManager.activeStorage(withDomain = domain)
const path = UTSiOS.getDataPath()
storage!.rootPath = path
this.migrateStorage(storage!)
}
this.storage = storage
return storage!
}
}
export const setStorage: SetStorage = function (options: SetStorageOptions) {
setTimeout(() => {
uni_setStorageAsync(options, (itemKey: string, itemData: string) => {
StorageTool.getStorage().setItemPersistent(itemKey, value = itemData, callback = null)
}, (itemKey: string) => {
StorageTool.getStorage().removeItem(itemKey, callback = null)
})
}, 0)
}
export const setStorageSync: SetStorageSync = function (key: string, data: any) {
uni_setStorageSync(key, data, (itemKey: string, itemValue: string) => {
StorageTool.getStorage().setItemPersistent(itemKey, value = itemValue, callback = null)
}, (itemKey: string) => {
StorageTool.getStorage().removeItem(itemKey, callback = null)
})
}
function getItemAsync(itemKey: string): string | null {
return StorageTool.getStorage().getItem(itemKey, callback = null)
}
function includeKey(key: string): boolean {
let storage = StorageTool.getStorage()
let list = storage.getAllKeys()
if (list != null) {
let item = list!.find((value): boolean => {
if (typeof value == "string") {
return (value as string) == key;
}
return false;
})
return (item != null);
}
return false;
}
export const getStorage: GetStorage = function (options: GetStorageOptions) {
setTimeout(() => {
uni_getStorageAsync(options, getItemAsync, includeKey)
}, 0);
}
export const getStorageSync: GetStorageSync = function (key: string): any {
return uni_getStorageSync(key, getItemAsync)
}
export const getStorageInfo: GetStorageInfo = function (options: GetStorageInfoOptions) {
setTimeout(() => {
const storage = StorageTool.getStorage()
const allKeys = storage.getAllKeys()
const length = storage.length()
const limitSize = 1.7976931348623157e+308
const success: GetStorageInfoSuccess = {
keys: allKeys,
currentSize: length,
limitSize: limitSize
}
options.success?.(success)
options.complete?.(success)
}, 0);
}
export const getStorageInfoSync: GetStorageInfoSync = function () : GetStorageInfoSuccess {
const storage = StorageTool.getStorage()
const allKeys = storage.getAllKeys()
const length = storage.length()
const limitSize = 1.7976931348623157e+308
const success: GetStorageInfoSuccess = {
keys: allKeys,
currentSize: length,
limitSize: limitSize
}
return success
}
export const removeStorage: RemoveStorage = function (options: RemoveStorageOptions) {
setTimeout(() => {
StorageTool.getStorage().removeItem(options.key, callback = null)
let success: RemoveStorageSuccess = {
}
options.success?.(success)
options.complete?.(success)
}, 0);
}
export const removeStorageSync: RemoveStorageSync = function (key: string) {
StorageTool.getStorage().removeItem(key, callback = null)
}
export const clearStorage: ClearStorage = function (option: ClearStorageOptions | null) {
setTimeout(() => {
StorageTool.getStorage().clear()
let success: ClearStorageSuccess = {
}
if (option != null) {
option!.success?.(success)
option!.complete?.(success)
}
}, 0);
}
export const clearStorageSync: ClearStorageSync = function () {
StorageTool.getStorage().clear()
}
/**
* uni.setStorage成功回调参数
*/
export type SetStorageSuccess = {
}
/**
* uni.setStorage成功回调函数定义
*/
export type SetStorageSuccessCallback = (res: SetStorageSuccess) => void
/**
* uni.setStorage失败回调函数定义
*/
export type SetStorageFailCallback = (res: UniError) => void
/**
* uni.setStorage完成回调函数定义
*/
export type SetStorageCompleteCallback = (res: any) => void
/**
* uni.setStorage参数定义
*/
export type SetStorageOptions = {
/**
* 本地存储中的指定的 key
*/
key: string,
/**
* 需要存储的内容,只支持原生类型、及能够通过 JSON.stringify 序列化的对象
*/
data: any,
/**
* 接口调用成功的回调函数
*/
success?: SetStorageSuccessCallback | null,
/**
* 接口调用失败的回调函数
*/
fail?: SetStorageFailCallback | null,
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: SetStorageCompleteCallback | null
}
export type SetStorage = (options: SetStorageOptions) => void
export type SetStorageSync = (key: string, data: any) => void
/**
* uni.getStorage成功回调参数
*/
export type GetStorageSuccess = {
/**
* key 对应的内容
*/
data: any | null
}
/**
* uni.getStorage成功回调函数定义
*/
export type GetStorageSuccessCallback = (res: GetStorageSuccess) => void
/**
* uni.getStorage失败回调函数定义
*/
export type GetStorageFailCallback = (res: UniError) => void
/**
* uni.getStorage完成回调函数定义
*/
export type GetStorageCompleteCallback = (res: any) => void
/**
* uni.getStorage参数定义
*/
export type GetStorageOptions = {
/**
* 本地存储中的指定的 key
*/
key: string,
/**
* 接口调用成功的回调函数
*/
success?: GetStorageSuccessCallback | null,
/**
* 接口调用失败的回调函数
*/
fail?: GetStorageFailCallback | null,
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: GetStorageCompleteCallback | null
}
export type GetStorage = (options: GetStorageOptions) => void
export type GetStorageSync = (key: string) => any | null
/**
* uni.getStorageInfo成功回调参数
*/
export type GetStorageInfoSuccess = {
/**
* 当前 storage 中所有的 key
*/
keys: Array<string>,
/**
* 当前占用的空间大小, 单位:kb
*/
currentSize: number,
/**
* 限制的空间大小, 单位:kb
*/
limitSize: number,
}
/**
* uni.getStorageInfo成功回调函数定义
*/
export type GetStorageInfoSuccessCallback = (res: GetStorageInfoSuccess) => void
/**
* uni.getStorageInfo失败回调函数定义
*/
export type GetStorageInfoFailCallback = (res: UniError) => void
/**
* uni.getStorageInfo完成回调函数定义
*/
export type GetStorageInfoCompleteCallback = (res: any) => void
/**
* uni.getStorageInfo参数定义
*/
export type GetStorageInfoOptions = {
/**
* 接口调用成功的回调函数
*/
success?: GetStorageInfoSuccessCallback | null,
/**
* 接口调用失败的回调函数
*/
fail?: GetStorageInfoFailCallback | null,
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: GetStorageInfoCompleteCallback | null
}
export type GetStorageInfo = (options: GetStorageInfoOptions) => void
export type GetStorageInfoSync = () => GetStorageInfoSuccess
/**
* uni.removeStorage成功回调参数
*/
export type RemoveStorageSuccess = {
}
/**
* uni.removeStorage成功回调函数定义
*/
export type RemoveStorageSuccessCallback = (res: RemoveStorageSuccess) => void
/**
* uni.removeStorage失败回调函数定义
*/
export type RemoveStorageFailCallback = (res: UniError) => void
/**
* uni.removeStorage完成回调函数定义
*/
export type RemoveStorageCompleteCallback = (res: any) => void
/**
* uni.removeStorage参数定义
*/
export type RemoveStorageOptions = {
/**
* 本地存储中的指定的 key
*/
key: string,
/**
* 接口调用的回调函数
*/
success?: RemoveStorageSuccessCallback | null,
/**
* 接口调用失败的回调函数
*/
fail?: RemoveStorageFailCallback | null,
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: RemoveStorageCompleteCallback | null
}
export type RemoveStorage = (options: RemoveStorageOptions) => void
export type RemoveStorageSync = (key: string) => void
/**
* uni.clearStorage 成功返回数据结构
*/
export type ClearStorageSuccess = {
}
/**
* uni.clearStorage 成功回调函数定义
*/
export type ClearStorageSuccessCallback = (res: ClearStorageSuccess) => void
/**
* uni.clearStorage 失败回调函数定义
*/
export type ClearStorageFailCallback = (res: UniError) => void
/**
* uni.clearStorage 完成回调函数定义
*/
export type ClearStorageCompleteCallback = (res: any) => void
/**
* uni.removeStorage参数定义
*/
export type ClearStorageOptions = {
/**
* 接口调用的回调函数
*/
success?: ClearStorageSuccessCallback | null,
/**
* 接口调用失败的回调函数
*/
fail?: ClearStorageFailCallback | null,
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: ClearStorageCompleteCallback | null
}
export type ClearStorage = (option?: ClearStorageOptions | null) => void
export type ClearStorageSync = () => void
export interface Uni {
/**
* uni.setStorage函数定义
* 将数据存储在本地storage存储中指定的 key 中,会覆盖掉原来该 key 对应的内容,这是一个异步接口。
*
* @param {SetStorageOptions} options
* @tutorial https://uniapp.dcloud.net.cn/api/storage/storage.html#setstorage
* @uniPlatform {
* "app": {
* "android": {
* "osVer": "4.4.4",
* "uniVer": "2.0.3",
* "unixVer": "3.9.0"
* },
* "ios": {
* "osVer": "9.0",
* "uniVer": "2.0.3",
* "unixVer": "3.9.0"
* }
* }
* }
* @uniVersion 2.0.3
* @uniVueVersion 2,3 //支持的vue版本
*/
setStorage(options: SetStorageOptions) : void,
/**
* uni.setStorageSync函数定义
* 将 data 存储在本地storage存储中指定的 key 中,会覆盖掉原来该 key 对应的内容,这是一个同步接口。
*
* @param {string} key 本地storage存储中的指定的 key
* @param {any} data 需要存储的内容,只支持原生类型、及能够通过 JSON.stringify 序列化的对象
* @tutorial https://uniapp.dcloud.net.cn/api/storage/storage.html#setstoragesync
* @uniPlatform {
* "app": {
* "android": {
* "osVer": "4.4.4",
* "uniVer": "2.0.3",
* "unixVer": "3.9.0"
* },
* "ios": {
* "osVer": "9.0",
* "uniVer": "2.0.3",
* "unixVer": "3.9.0"
* }
* }
* }
* @uniVersion 2.0.3
* @uniVueVersion 2,3 //支持的vue版本
*/
setStorageSync(key: string, data: any) : void,
/**
* uni.getStorage函数定义
* 从本地存储中异步获取指定 key 对应的内容。
*
* @param {GetStorageOptions} options
* @tutorial https://uniapp.dcloud.net.cn/api/storage/storage.html#getstorage
* @uniPlatform {
* "app": {
* "android": {
* "osVer": "4.4.4",
* "uniVer": "2.0.3",
* "unixVer": "3.9.0"
* },
* "ios": {
* "osVer": "9.0",
* "uniVer": "2.0.3",
* "unixVer": "3.9.0"
* }
* }
* }
* @uniVersion 2.0.3
* @uniVueVersion 2,3 //支持的vue版本
*/
getStorage(options: GetStorageOptions) : void,
/**
* uni.getStorageSync函数定义
* 从本地存储中同步获取指定 key 对应的内容。
*
* @param {string} key 本地存储中的指定的 key
* @tutorial https://uniapp.dcloud.net.cn/api/storage/storage.html#getstoragesync
* @uniPlatform {
* "app": {
* "android": {
* "osVer": "4.4.4",
* "uniVer": "2.0.3",
* "unixVer": "3.9.0"
* },
* "ios": {
* "osVer": "9.0",
* "uniVer": "2.0.3",
* "unixVer": "3.9.0"
* }
* }
* }
* @uniVersion 2.0.3
* @uniVueVersion 2,3 //支持的vue版本
*/
getStorageSync(key: string) : any | null,
/**
* uni.getStorageInfo函数定义
* 异步获取当前 storage 的相关信息。
*
* @param {GetStorageInfoOptions} options
* @tutorial https://uniapp.dcloud.net.cn/api/storage/storage.html#getstorageinfo
* @uniPlatform {
* "app": {
* "android": {
* "osVer": "4.4.4",
* "uniVer": "2.0.3",
* "unixVer": "3.9.0"
* },
* "ios": {
* "osVer": "9.0",
* "uniVer": "2.0.3",
* "unixVer": "3.9.0"
* }
* }
* }
* @uniVersion 2.0.3
* @uniVueVersion 2,3 //支持的vue版本
*/
getStorageInfo(options: GetStorageInfoOptions) : void,
/**
* uni.getStorageInfoSync函数定义
* 同步获取当前 storage 的相关信息。
*
*
* @tutorial https://uniapp.dcloud.net.cn/api/storage/storage.html#getstorageinfosync
*
* @uniPlatform {
* "app": {
* "android": {
* "osVer": "4.4.4",
* "uniVer": "2.0.3",
* "unixVer": "3.9.0"
* },
* "ios": {
* "osVer": "9.0",
* "uniVer": "2.0.3",
* "unixVer": "3.9.0"
* }
* }
* }
* @uniVersion 2.0.3
* @uniVueVersion 2,3 //支持的vue版本
*/
getStorageInfoSync() : GetStorageInfoSuccess,
/**
* uni.removeStorage函数定义
* 从本地存储中异步移除指定 key。
*
* @param {RemoveStorageOptions} options
*
* @tutorial hhttps://uniapp.dcloud.net.cn/api/storage/storage.html#removestorage
*
* @uniPlatform {
* "app": {
* "android": {
* "osVer": "4.4.4",
* "uniVer": "2.0.3",
* "unixVer": "3.9.0"
* },
* "ios": {
* "osVer": "9.0",
* "uniVer": "2.0.3",
* "unixVer": "3.9.0"
* }
* }
* }
* @uniVersion 2.0.3
* @uniVueVersion 2,3 //支持的vue版本
*/
removeStorage(options: RemoveStorageOptions) : void,
/**
* uni.removeStorageSync函数定义
* 从本地存储中同步移除指定 key。
*
* @param {string} key 本地存储中的指定的 key
*
* @tutorial https://uniapp.dcloud.net.cn/api/storage/storage.html#removestoragesync
*
* @uniPlatform {
* "app": {
* "android": {
* "osVer": "4.4.4",
* "uniVer": "2.0.3",
* "unixVer": "3.9.0"
* },
* "ios": {
* "osVer": "9.0",
* "uniVer": "2.0.3",
* "unixVer": "3.9.0"
* }
* }
* }
* @uniVersion 2.0.3
* @uniVueVersion 2,3 //支持的vue版本
*/
removeStorageSync(key: string) : void,
/**
* uni.clearStorage函数定义
* 清除本地数据存储。
*
* @tutorial https://uniapp.dcloud.net.cn/api/storage/storage.html#clearstorage
*
* @uniPlatform {
* "app": {
* "android": {
* "osVer": "4.4.4",
* "uniVer": "2.0.3",
* "unixVer": "3.9.0"
* },
* "ios": {
* "osVer": "9.0",
* "uniVer": "2.0.3",
* "unixVer": "3.9.0"
* }
* }
* }
* @uniVersion 2.0.3
* @uniVueVersion 2,3 //支持的vue版本
*/
clearStorage(option?: ClearStorageOptions | null) : void,
/**
* uni.clearStorageSync函数定义
* 清除本地数据存储。
*
* @tutorial https://uniapp.dcloud.net.cn/api/storage/storage.html#clearstoragesync
*
* @uniPlatform {
* "app": {
* "android": {
* "osVer": "4.4.4",
* "uniVer": "2.0.3",
* "unixVer": "3.9.0"
* },
* "ios": {
* "osVer": "9.0",
* "uniVer": "2.0.3",
* "unixVer": "3.9.0"
* }
* }
* }
* @uniVersion 2.0.3
* @uniVueVersion 2,3 //支持的vue版本
*/
clearStorageSync() : void
}
import { SetStorageOptions, SetStorageSuccess, GetStorageOptions, GetStorageSuccess } from "./interface.uts"
const STORAGE_DATA_TYPE = '__TYPE'
const STORAGE_KEYS = 'uni-storage-keys'
/**
* add since 2023-09-04 过滤原生数据类型对齐 web typeOf 用于兼容旧数据
*/
function filterNativeType(src:string):string{
if(src == "Double" || src == "Float" || src == "Long" || src == "Int" || src == "Short" || src == "Byte" || src == "UByte" || src == "UShort" || src == "UInt" || src == "ULong"){
return "number"
}
return src
}
function parseValue(value: any): any | null {
const types = ['object', 'string', 'number', 'boolean', 'undefined']
const object = typeof value == 'string' ? JSON.parse(value as string) : value
if (object == null) {
return null
} else {
const type = typeof object
if (types.indexOf(type) >= 0) {
// @ts-expect-error
if (object instanceof UTSJSONObject || object instanceof Map<string,any>) {
// @ts-expect-error
const map = (object instanceof UTSJSONObject) ? (object as UTSJSONObject).toMap() : (object as Map<string,any>)
if (map.size == 2 && map.has('data') && map.has('type')) {
let dataType:string = ""
if(map.get("type") == null){
dataType = ""
}else{
dataType = map.get("type") as string
}
if (filterNativeType(typeof map.get('data')) == dataType && dataType != 'string') {
return map.get('data')
}else if (typeof map.get('data') == dataType && dataType == 'string') {
const regex = /^\d{4}-\d{2}-\d{2}T\d{2}\:\d{2}\:\d{2}\.\d{3}Z$/
// @ts-expect-error
if (type == 'object' && regex.test(map.get('data') as string)) {
let dateStr = map.get('data') as string
return new Date(dateStr)
}
return map.get('data')
}
} else if (map.size >= 1){
return ''
}
}
}
return null
}
}
function praseGetStorage(type: string, value: string): any | null {
let data: any | null = value
if (type != 'string' || (type == "string" && value == '{"type":"undefined"}')) {
// 兼容H5和V3初期历史格式
let object = JSON.parse(value)
if (object == null) {
return data
}
const result = parseValue(object)
if (result != null) {
data = result
} else if (type != null){
// 兼容App端历史格式
data = object
if (typeof object == 'string') {
object = JSON.parse(object as string)
const objectType = typeof object
if (objectType == 'number' && type == 'date') {
let dateNum = object as number
data = new Date(dateNum)
} else if (objectType == (['null', 'array'].indexOf(type) < 0 ? type : 'object')) {
data = object
}
}
}
}
return data
}
function uni_setStorageSync(key: string, data: any, saveItemHandler: (key: string, data: string) => void, removeItemHandler: (key: string) => void) {
let type = filterNativeType(typeof data)
let value: string | null = null
value = (type == 'string') ? (data as string) : JSON.stringify({type: type, data: data})
if (type == 'string' && parseValue(data) != null) {
saveItemHandler(key + STORAGE_DATA_TYPE, type)
} else{
removeItemHandler(key + STORAGE_DATA_TYPE)
}
if(value == null){
value = ""
}
saveItemHandler(key, value!)
}
function uni_setStorageAsync(options: SetStorageOptions, saveItemAsyncHandler: (key: string, data: string) => void, removeItemAsyncHandler: (key: string) => void) {
const type = filterNativeType(typeof options.data)
let value: string | null = null
value = (type == 'string') ? (options.data as string) : JSON.stringify({type: type, data: options.data})
if (value == null) {
let fail = new UniError("uni-storage", -1, "data can not be stringify")
options.fail?.(fail)
options.complete?.(fail)
} else{
if (type == 'string' && parseValue(options.data) != null) {
saveItemAsyncHandler(options.key + STORAGE_DATA_TYPE, type)
} else{
removeItemAsyncHandler(options.key + STORAGE_DATA_TYPE)
}
if(value == null){
value = ""
}
saveItemAsyncHandler(options.key, value!)
let success: SetStorageSuccess = {
}
options.success?.(success)
options.complete?.(success)
}
}
function uni_getStorageSync(key: string, getItemHandler: ((key: string) => string | null)): any | null {
let value = getItemHandler(key)
let typeOrigin = getItemHandler(key + STORAGE_DATA_TYPE)
if(typeOrigin == null){
typeOrigin = ""
}
const type = typeOrigin!.toLowerCase()
if (typeof value != "string") {
return ''
}
if(value == null){
value = ""
}
return praseGetStorage(type, value!)
}
function uni_getStorageAsync(options: GetStorageOptions, getItemAsyncHandler: ((key: string) => string | null), includesKey: (key: string) => boolean) {
let ret = includesKey(options.key);
if (!ret) {
let fail = new UniError("uni-storage", -2, "getStorage:fail data not found")
options.fail?.(fail);
options.complete?.(fail);
return;
}
let value = getItemAsyncHandler(options.key)
if(value == null){
value = ""
}
let typeOrigin = getItemAsyncHandler(options.key + STORAGE_DATA_TYPE)
if(typeOrigin == null){
typeOrigin = ""
}
const type = typeOrigin!.toLowerCase()
if (typeof value != "string") {
let success: GetStorageSuccess = {
data: ""
}
options.success?.(success)
options.complete?.(success)
}else {
const data = praseGetStorage(type, value!)
let success: GetStorageSuccess = {
data: data
}
options.success?.(success)
options.complete?.(success)
}
}
export {
STORAGE_DATA_TYPE,
STORAGE_KEYS,
uni_setStorageSync,
uni_setStorageAsync,
uni_getStorageSync,
uni_getStorageAsync,
}
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册