class LazyLoader {
constructor(dataManager) {
this.dataManager = dataManager;
this.cache = new Map();
this.entityTypeMap = {
bancai: 'bancais',
dingdan: 'dingdans',
mupi: 'mupis',
chanpin: 'chanpins',
kucun: 'kucuns',
dingdan_bancai: 'dingdan_bancais',
chanpin_zujian: 'chanpin_zujians',
zujian: 'zujians',
caizhi: 'caizhis',
dingdan_chanpin: 'dingdan_chanpins',
user: 'users',
jinhuo: 'jinhuos'
};
}
createProxy(entity, entityType) {
if (entity.__isProxy) return entity;
const handler = {
get: (target, prop) => {
if (typeof target[prop] !== 'object' || target[prop] === null) {
return target[prop];
}
console.log(entity)
const refType = this.getReferenceType(prop);
if (!refType) return target[prop];
if (Array.isArray(target[prop])) {
return this.loadReferences(target[prop], refType);
}
return this.loadReference(target[prop], refType);
}
};
entity.__isProxy = true;
return new Proxy(entity, handler);
}
getReferenceType(prop) {
const baseProp = prop.replace(/\d/g, '');
if (this.entityTypeMap[baseProp]) return this.entityTypeMap[baseProp];
const pluralProp = `${baseProp}s`;
if (this.dataManager._rawData[pluralProp]) return pluralProp;
return null;
}
loadReference(ref, refType) {
console.log(entity)
if (!ref?.id) return ref;
const cacheKey = `${refType}_${ref.id}`;
if (this.cache.has(cacheKey)) return this.cache.get(cacheKey);
const entities = this.dataManager._rawData[refType] || [];
const entity = entities.find(e => e.id === ref.id);
console.log(entity)
if (!entity) return ref;
const resolvedEntity = this.resolveReferences({...entity});
const proxy = this.createProxy(resolvedEntity, refType);
this.cache.set(cacheKey, proxy);
console.log(entity)
return proxy;
}
loadReferences(refs, refType) {
return refs.map(ref => this.loadReference(ref, refType));
}
resolveReferences(entity) {
for (const attr in entity) {
const refType = this.getReferenceType(attr);
if (!refType) continue;
if (Array.isArray(entity[attr])) {
entity[attr] = entity[attr].map(item =>
this.dataManager._rawData[refType]?.find(e => e.id === item.id) || item
);
} else if (entity[attr]?.id) {
entity[attr] =
this.dataManager._rawData[refType]?.find(e => e.id === entity[attr].id) ||
entity[attr];
}
}
return entity;
}
clearCache() {
this.cache.clear();
}
}
class MiniProgramDataManager {
constructor(baseUrl = '') {
this.baseUrl = baseUrl;
this.debug = true;
this.networkAvailable = false;
this.isSyncing = false;
this.lastSync = null;
this.syncInterval = 5 * 60 * 1000;
this.storageKey = 'miniProgramData';
this._rawData = this.createEmptyData();
this.lazyLoader = new LazyLoader(this);
this.callbacks = {
all: [],
bancais: [], dingdans: [], mupis: [], chanpins: [], kucuns: [],
chanpin_zujians: [], dingdan_bancais: [], zujians: [], caizhis: [],
dingdan_chanpins: [], users: [], jinhuos: []
};
this.initNetwork();
this.loadDataFromStorage();
this.startAutoSync();
}
createEmptyData() {
return {
bancais: [], dingdans: [], mupis: [], chanpins: [], kucuns: [],
dingdan_bancais: [], chanpin_zujians: [], zujians: [], caizhis: [],
dingdan_chanpins: [], users: [], jinhuos: [],
_lastModified: null, _lastSync: null
};
}
get data() {
const handler = {
get: (target, prop) => {
if (prop.startsWith('_')) return target[prop];
if (Array.isArray(target[prop])) {
return target[prop].map(item =>
this.lazyLoader.createProxy(item, prop.replace(/s$/, ''))
);
}
return target[prop];
},
set: (target, prop, value) => {
target[prop] = value;
return true;
}
};
return new Proxy(this._rawData, handler);
}
async initialize() {
try {
await this.syncData();
return true;
} catch (error) {
if (this._rawData._lastSync) return true;
throw error;
}
}
startAutoSync() {
this.autoSyncTimer = setInterval(() => {
!this.isSyncing && this.syncData();
}, this.syncInterval);
}
stopAutoSync() {
clearInterval(this.autoSyncTimer);
}
async initNetwork() {
try {
const { networkType } = await wx.getNetworkType();
this.networkAvailable = networkType !== 'none';
} catch {
this.networkAvailable = false;
}
}
async syncData() {
if (this.isSyncing) return;
this.isSyncing = true;
try {
const since = this._rawData._lastSync;
await this.fetchAll(since);
this.lazyLoader.clearCache();
this.saveDataToStorage();
this.triggerCallbacks('refresh', 'all', this.data);
} catch (error) {
console.error('Sync failed:', error);
this.triggerCallbacks('sync_error', 'all', { error });
if (!this._rawData._lastSync) throw error;
} finally {
this.isSyncing = false;
}
}
async fetchAll(since) {
try {
const params = since ? { since } : {};
const resolvedData = this.baseUrl
? await this.request('/app/all', 'GET', params)
: this.createEmptyData();
Object.keys(this._rawData).forEach(key => {
if (key.startsWith('_') || !resolvedData[key]) return;
if (since) {
resolvedData[key].forEach(newItem => {
const index = this._rawData[key].findIndex(item => item.id === newItem.id);
index >= 0
? this._rawData[key][index] = newItem
: this._rawData[key].push(newItem);
});
} else {
this._rawData[key] = resolvedData[key];
}
});
this._rawData._lastSync = new Date().toISOString();
this.saveDataToStorage();
console.log( this._rawData)
return true;
} catch (error) {
console.error('Fetch error:', error);
this.triggerCallbacks('fetch_error', 'all', { error });
throw error;
}
}
async request(url, method, data, retryCount = 3) {
return new Promise((resolve, reject) => {
const fullUrl = `${this.baseUrl}${url}`;
const requestTask = () => {
wx.request({
url: fullUrl,
method,
data,
header: { 'Content-Type': 'application/json' },
success: (res) => {
if (res.statusCode >= 200 && res.statusCode < 300) {
resolve(res.data);
} else {
const err = new Error(res.data?.message || 'API error');
retryCount > 1
? setTimeout(requestTask, 1000, retryCount - 1)
: reject(err);
}
},
fail: (err) => {
retryCount > 1
? setTimeout(requestTask, 1000, retryCount - 1)
: reject(new Error(`Network error: ${err.errMsg}`));
}
});
};
requestTask();
});
}
registerCallback(entity, callback) {
this.callbacks[entity]?.push(callback) || this.callbacks.all.push(callback);
}
unregisterCallback(entity, callback) {
const arr = this.callbacks[entity] || this.callbacks.all;
const index = arr.indexOf(callback);
if (index !== -1) arr.splice(index, 1);
}
triggerCallbacks(operation, entity, data) {
this.callbacks.all.forEach(cb => cb(operation, entity, data));
this.callbacks[entity]?.forEach(cb => cb(operation, data));
}
async crudOperation(operation, entity, data) {
try {
const result = await this.request(`/app/${operation}/${entity}`, 'POST', data);
this.updateLocalData(operation, entity, result || data);
this.triggerCallbacks(operation, entity, result || data);
return result;
} catch (error) {
this.triggerCallbacks(`${operation}_error`, entity, { data, error });
throw error;
}
}
updateLocalData(operation, entity, data) {
const key = `${entity}s`;
const collection = this._rawData[key] || [];
switch (operation) {
case 'add':
collection.push(data);
break;
case 'update':
const index = collection.findIndex(item => item.id === data.id);
index >= 0
? collection[index] = data
: collection.push(data);
break;
case 'delete':
const deleteIndex = collection.findIndex(item => item.id === data.id);
if (deleteIndex >= 0) collection.splice(deleteIndex, 1);
break;
}
this._rawData._lastModified = new Date().toISOString();
this.lazyLoader.clearCache();
this.saveDataToStorage();
}
loadDataFromStorage() {
try {
const storedData = wx.getStorageSync(this.storageKey);
if (storedData) this._rawData = storedData;
} catch (error) {
console.error('Storage load error:', error);
}
}
saveDataToStorage() {
try {
wx.setStorageSync(this.storageKey, this._rawData);
} catch (error) {
console.error('Storage save error:', error);
wx.showToast({ title: '数据保存失败', icon: 'none' });
}
}
async addEntity(entity, data) {
return this.crudOperation('add', entity, data);
}
async updateEntity(entity, data) {
return this.crudOperation('update', entity, data);
}
async deleteEntity(entity, id) {
return this.crudOperation('delete', entity, { id });
}
async transactionalOperation(endpoint, data) {
try {
await this.request(`/app/Transactional/${endpoint}`, 'POST', data);
await this.syncData();
return true;
} catch (error) {
this.triggerCallbacks('transaction_error', endpoint, { data, error });
throw error;
}
}
}
module.exports = MiniProgramDataManager;
获取网络数据不到数据,但服务端数据已经发过来了
最新发布