@instantdb/core
Version:
Instant's core local abstraction
91 lines • 2.4 kB
JavaScript
function getAllTransactionChunkKeys() {
const v = 1;
const _dummy = {
__etype: v,
__ops: v,
create: v,
update: v,
link: v,
unlink: v,
delete: v,
merge: v,
ruleParams: v,
};
return new Set(Object.keys(_dummy));
}
const allTransactionChunkKeys = getAllTransactionChunkKeys();
function transactionChunk(etype, id, prevOps) {
const target = {
__etype: etype,
__ops: prevOps,
};
return new Proxy(target, {
get: (_target, cmd) => {
if (cmd === '__ops')
return prevOps;
if (cmd === '__etype')
return etype;
if (!allTransactionChunkKeys.has(cmd)) {
return undefined;
}
return (args, opts) => {
return transactionChunk(etype, id, [
...prevOps,
opts ? [cmd, etype, id, args, opts] : [cmd, etype, id, args],
]);
};
},
});
}
/**
* Creates a lookup to use in place of an id in a transaction
*
* @example
* db.tx.users[lookup('email', 'lyndon@example.com')].update({name: 'Lyndon'})
*/
export function lookup(attribute, value) {
return `lookup__${attribute}__${JSON.stringify(value)}`;
}
export function isLookup(k) {
return k.startsWith('lookup__');
}
export function parseLookup(k) {
const [_, attribute, ...vJSON] = k.split('__');
return [attribute, JSON.parse(vJSON.join('__'))];
}
function etypeChunk(etype) {
return new Proxy({
__etype: etype,
}, {
get(_target, cmd) {
if (cmd === '__etype')
return etype;
const id = cmd;
if (isLookup(id)) {
return transactionChunk(etype, parseLookup(id), []);
}
return transactionChunk(etype, id, []);
},
});
}
export function txInit() {
return new Proxy({}, {
get(_target, ns) {
return etypeChunk(ns);
},
});
}
/**
* A handy builder for changes.
*
* You must start with the `namespace` you want to change:
*
* @example
* db.tx.goals[goalId].update({title: "Get fit"})
* // Note: you don't need to create `goals` ahead of time.
*/
export const tx = txInit();
export function getOps(x) {
return x.__ops;
}
//# sourceMappingURL=instatx.js.map