@tanstack/db
Version:
A reactive client store for building super fast apps on sync
73 lines (72 loc) • 2.46 kB
JavaScript
;
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
const transactions = require("./transactions.cjs");
const errors = require("./errors.cjs");
function createPacedMutations(config) {
const { onMutate, mutationFn, strategy, ...transactionConfig } = config;
let activeTransaction = null;
const commitCallback = () => {
if (!activeTransaction) {
throw new Error(
`Strategy callback called but no active transaction exists. This indicates a bug in the strategy implementation.`
);
}
if (activeTransaction.state !== `pending`) {
throw new Error(
`Strategy callback called but active transaction is in state "${activeTransaction.state}". Expected "pending".`
);
}
const txToCommit = activeTransaction;
activeTransaction = null;
txToCommit.commit().catch(() => {
});
return txToCommit;
};
function mutate(variables) {
if (!activeTransaction || activeTransaction.state !== `pending`) {
activeTransaction = transactions.createTransaction({
...transactionConfig,
mutationFn,
autoCommit: false
});
}
activeTransaction.mutate(() => {
onMutate(variables);
});
const txToReturn = activeTransaction;
if (strategy._type === `queue`) {
activeTransaction = null;
let admitted;
try {
admitted = strategy.execute(() => {
txToReturn.commit().catch(() => {
});
return txToReturn;
});
} catch (error) {
if (!(error instanceof errors.QueueDisposedError)) throw error;
txToReturn.rollback({ error, isSecondaryRollback: true });
return txToReturn;
}
if (admitted === false) {
txToReturn.rollback({
error: new errors.QueueCapacityExceededError(),
isSecondaryRollback: true
});
}
} else {
const executed = strategy.execute(commitCallback);
if ((strategy._type === `debounce` || strategy._type === `throttle`) && executed === false) {
txToReturn.rollback({
error: strategy._type === `debounce` ? new errors.DebounceCallDroppedError() : new errors.ThrottleCallDroppedError(),
isSecondaryRollback: true
});
activeTransaction = null;
}
}
return txToReturn;
}
return mutate;
}
exports.createPacedMutations = createPacedMutations;
//# sourceMappingURL=paced-mutations.cjs.map