import AsyncStorage from '@react-native-async-storage/async-storage' interface AppBatchUploadConfig { /** * 数量量达到batchSize开始上报,默认10 */ batchSize?: number request: (data: any) => Promise } const localCacheKey = '__chushu_app_cache' async function getFromLocalStorage() { const res = await AsyncStorage.getItem(localCacheKey) if (res) { return JSON.parse(res) } return [] } async function saveToLocalStorage(data: any) { await AsyncStorage.setItem(localCacheKey, JSON.stringify(data)) } export class AppBatchUpload { public request: AppBatchUploadConfig['request'] private batchSize: number private _cacheList: any[] private cacheList: any[] private isUploading: boolean private _userHash: string public constructor(config: AppBatchUploadConfig) { // eslint-disable-next-line @typescript-eslint/no-this-alias const that = this this.batchSize = config.batchSize || 10 this.isUploading = false getFromLocalStorage().then(res => { this.cacheList = [...res] this._cacheList = new Proxy(this.cacheList, { get: function (target, cacheKey) { return Reflect.get(target, cacheKey) }, set: function (target, cacheKey, newValue) { const result = Reflect.set(target, cacheKey, newValue) if (cacheKey === 'length') { if (that.isUploading) { return result } if (newValue >= that.batchSize && that._userHash) { that.isUploading = true that.request(target.slice(0, that.batchSize)).then(requestRes => { requestRes && that.deleteCache() that.isUploading = false }) } } return result }, }) }) this.request = config.request } public addCache(data: any, cache = true, cb?: () => void) { if (!cache) { this.request(data).then(res => { res && cb?.() }) return } const inserted: any[] = Array.isArray(data) ? data : [data] this._cacheList.push(...inserted) saveToLocalStorage(this.cacheList) cb?.() } public setUserHash(hash: string) { this._userHash = hash } /** * 删除已上传数据 */ public deleteCache() { this.cacheList.splice(0, this.batchSize) saveToLocalStorage(this.cacheList) } } const createAppBatchUpload = (function () { let appBatchUploadIns: AppBatchUpload return (config: AppBatchUploadConfig) => { if (!appBatchUploadIns) { appBatchUploadIns = new AppBatchUpload(config) } return appBatchUploadIns } })() export default createAppBatchUpload