synapse-storage
Version:
Набор инструментов для управления состоянием и апи-запросами
56 lines (54 loc) • 1.99 kB
JavaScript
const syncBatchingMiddleware = (options = {})=>{
const batchSize = options.batchSize ?? 10;
let queue = [];
let scheduled = false;
const shouldBatch = (action)=>{
return action.type === 'set' || action.type === 'update';
};
const mergeActions = (actions)=>{
const merged = new Map();
for (const action of actions){
const key = `${action.type}_${action.key?.toString() || 'default'}`;
merged.set(key, action);
}
return Array.from(merged.values());
};
const flushQueue = (api, next)=>{
if (queue.length === 0) return;
const batch = queue.splice(0);
const mergedActions = mergeActions(batch);
for (const action of mergedActions){
next(action);
}
};
return {
name: 'sync-batching',
setup: ()=>{},
cleanup: ()=>{
queue = [];
scheduled = false;
},
reducer: (api)=>(next)=>(action)=>{
if (!shouldBatch(action)) {
return next(action);
}
queue.push(action);
if (queue.length >= batchSize) {
flushQueue(api, next);
} else if (!scheduled) {
scheduled = true;
queueMicrotask(()=>{
scheduled = false;
flushQueue(api, next);
});
}
// Возвращаем текущее значение из кеша (операция ещё не выполнена если в очереди)
if (action.type === 'set' && action.key) {
return action.value;
}
return undefined;
}
};
};
export { syncBatchingMiddleware };
//# sourceMappingURL=sync-storage-batching.middleware.js.map