@snap/camera-kit
Version:
Camera Kit Web
45 lines • 2 kB
JavaScript
import { __awaiter } from "tslib";
import { createMappingHandler } from "./mappingHandler";
export const createBatchingHandler = ({ batchReduce, isBatchComplete, maxBatchAge, pageVisibility, }) => {
let batchTimeout;
let currentBatch = undefined;
let clearOnHidden = () => { };
const reducingHandler = createMappingHandler((request) => __awaiter(void 0, void 0, void 0, function* () {
currentBatch = yield batchReduce(currentBatch, request);
return currentBatch;
}), pageVisibility, 1);
const batchAndSend = (next, request, metadata) => {
const batch = request ? batchReduce(currentBatch, request) : currentBatch;
if (!batch)
return;
const complete = batch instanceof Promise
? batch.then((b) => next(b, metadata)).catch(() => { })
: next(batch, metadata).catch(() => { });
currentBatch = undefined;
clearTimeout(batchTimeout);
clearOnHidden();
return complete;
};
return (next) => (request, metadata) => __awaiter(void 0, void 0, void 0, function* () {
if (pageVisibility && pageVisibility.isDuringVisibilityTransition("hidden")) {
yield batchAndSend(next, request, metadata);
return;
}
if (currentBatch === undefined) {
const sendBatch = () => batchAndSend(next, undefined, metadata);
if (maxBatchAge !== undefined)
batchTimeout = setTimeout(sendBatch, maxBatchAge);
if (pageVisibility)
clearOnHidden = pageVisibility.onPageHidden(sendBatch);
}
const handle = reducingHandler(() => __awaiter(void 0, void 0, void 0, function* () {
if (!currentBatch)
return;
if (!isBatchComplete(currentBatch))
return;
yield batchAndSend(next, undefined, metadata);
}));
return handle(request, metadata);
});
};
//# sourceMappingURL=batchingHandler.js.map