UNPKG

@instantdb/core

Version:

Instant's core local abstraction

99 lines 2.59 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.tx = void 0; exports.lookup = lookup; exports.isLookup = isLookup; exports.parseLookup = parseLookup; exports.txInit = txInit; exports.getOps = getOps; 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'}) */ function lookup(attribute, value) { return `lookup__${attribute}__${JSON.stringify(value)}`; } function isLookup(k) { return k.startsWith('lookup__'); } 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, []); }, }); } 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. */ exports.tx = txInit(); function getOps(x) { return x.__ops; } //# sourceMappingURL=instatx.js.map