triplit-tanstackdb
Version:
TanStack DB collection adapter for the Triplit real-time, offline-first sync engine. Enables powerful optimistic updates and reactive, cross-source queries.
2 lines (1 loc) • 1.37 kB
JavaScript
import{createCollection as O}from"@tanstack/db";function C(y){let{client:o,query:c,getKey:r,onError:e}=y,a=c.collectionName;return{getKey:r,sync:{sync:i=>{let{begin:t,write:d,commit:g,markReady:T,collection:x}=i,l=!1,m,f=n=>{t();let I=Array.from(x.state.values()),M=new Set(I.map(r)),h=n?Array.from(n.values()):[],Q=new Set(h.map(r));for(let s of M)if(!Q.has(s)){let u=I.find(S=>r(S)===s);u&&d({type:"delete",value:u})}for(let s of h){let u=r(s);M.has(u)?d({type:"update",value:s}):d({type:"insert",value:s})}g()};return o.fetch(c).then(n=>{l||(f(n),T(),l=!0)}).catch(n=>{console.error("[Triplit Adapter] Initial fetch failed, waiting for subscription.",n),e==null||e(n)}),m=o.subscribe(c,n=>{f(n),l||(T(),l=!0)},n=>{console.error("[Triplit Adapter] Subscription error:",n),e==null||e(n)}),()=>{m==null||m()}}},onInsert:async({transaction:i})=>{try{for(let t of i.mutations)await o.insert(a,t.modified)}catch(t){throw e==null||e(t),t}},onUpdate:async({transaction:i})=>{try{for(let t of i.mutations)await o.update(a,String(t.key),t.changes)}catch(t){throw e==null||e(t),t}},onDelete:async({transaction:i})=>{try{for(let t of i.mutations)await o.delete(a,String(t.key))}catch(t){throw e==null||e(t),t}}}}function E(y){let{client:o,query:c,getKey:r,onError:e,...a}=y,p=C({client:o,query:c,getKey:r,onError:e});return O({...a,...p})}export{E as createTriplitCollection};