diffable-objects
Version:
A package for dynamic state tracking for Cloudflare's Durable Objects using SQLite
30 lines (29 loc) • 1.05 kB
JavaScript
import { state } from "./index.js";
import { unreachable } from "./util.js";
export function diffable() {
// biome-ignore lint/style/noArguments: <explanation>
const args = arguments;
const fn = (opts = {}) => (_, { kind, name: fieldName }) => {
if (kind === "field") {
return function (initialValue) {
const fieldNameNonPrivate = fieldName.replace(/^#/, "");
return state(this.ctx, opts.name ?? fieldNameNonPrivate, initialValue, {
snapshotPolicy: opts.snapshotPolicy ?? { changes: 10 },
});
};
}
throw new Error("Only fields can be persistable");
};
if (args.length === 0) {
return fn();
}
if (args.length === 1) {
const [optsOrName] = args;
if (typeof optsOrName === "object") {
return fn(optsOrName);
}
return fn(optsOrName ? { name: optsOrName } : {});
}
const [value, metadata] = args;
return fn()(value, metadata ?? unreachable());
}