UNPKG

@supabase-kit/react

Version:

> Hooks by management data from supabase and fetch data by react.

2 lines (1 loc) 8.94 kB
import{useQuery as b,useQueryClient as g}from"@tanstack/react-query";import{useEffect as Q,useMemo as p}from"react";import{useInfiniteQuery as S,useQuery as k}from"@tanstack/react-query";var T=({table:x,queryKey:J})=>{return[x,...J].join("_")};var m={match:(x,J={})=>{return x.match(J)},or:(x,J=[])=>{for(let X of J)x=x.or(X);return x},filter:(x,J={})=>{for(let[X,U]of Object.entries(J))x=x.filter(X,...U);return x},not:(x,J={})=>{for(let[X,[U,V]]of Object.entries(J))x=x.not(X,U,V);return x},textSearch:(x,J={})=>{for(let X of Object.keys(J)){let{text:U,options:V}=J[X];x=x.textSearch(X,U,V)}return x},limit:(x,J)=>{return x.limit(J)},single:(x)=>{return x=x.single()},maybeSingle:(x)=>{return x.maybeSingle()},csv:(x)=>{return x.csv()},explain:(x,J={})=>{return x.explain(J)},order:(x,J)=>{for(let[X,U]of Object.entries(J))x=x.order(X,U);return x},range:(x,J)=>{let X=(U)=>{return x.range(U.from,U.to,U.options)};if(!Array.isArray(J))return X(J);for(let U of J)x=X(U);return x}},q=new Set(["eq","neq","in","is","lt","lte","gt","gte","like","ilike","contains","containedBy","rangeGt","rangeGte","rangeLt","rangeLte","rangeAdjacent","overlaps"]),_=({where:x={},...J},X)=>{let U=(V,Z)=>{let G=m[V];if(G){X=G(X,Z);return}if(!q.has(V))return;for(let[$,I]of Object.entries(Z))X=X[V]($,I)};for(let V of Object.keys(x)){let Z=V in J?J[V]:x[V];U(V,Z)}for(let V of Object.keys(J)){if(V in x)continue;U(V,J[V])}return X};var D=(x)=>{function J({table:U,schema:V="public",column:Z="*",count:G,head:$,options:I={},single:Y,enabled:H,...L}){let N=async(R)=>{let B=(!V?x:x.schema(V)).from(U).select(Z,{count:G,head:$}),K=_(L,B),{data:A,error:P,count:O}=await K.abortSignal(R);if(P)throw P;return{count:O??0,payload:$?Y?null:[]:Y?A??{}:A??[]}},{queryKey:z=[],...W}=I,M=T({table:U,queryKey:z});return k({queryKey:[M,L.where,L.limit,Y,G,$,U,Z,G,I,Y,H],queryFn:({signal:R})=>N(R),enabled:H,...W})}return{useSupaInfiniteQuery:({table:U,schema:V="public",column:Z="*",options:G,enabled:$,count:I="exact",head:Y,...H})=>{let L=async(R)=>{let B=(!V?x:x.schema(V)).from(U).select(Z,{count:I,head:Y}),K=_(H,B),{data:A,error:P,count:O}=await K.abortSignal(R);if(P)throw P;return{count:O??0,payload:Y?[]:A??[]}},{initialData:N,queryKey:z=[],...W}=G,M=T({table:U,queryKey:["infinite",...z]});return S({queryKey:[M,H.where,H.limit,Y],queryFn:({signal:R})=>L(R),enabled:$,...W})},useSupaQuery:J,QueryBuilder:_}};import{useCallback as j,useEffect as f,useMemo as v}from"react";import{REALTIME_POSTGRES_CHANGES_LISTEN_EVENT as C}from"@supabase/supabase-js";import{useQueryClient as w}from"@tanstack/react-query";var E=(x,J)=>{let X=({table:V,schema:Z,event:G="*",where:$,type:I="postgres_changes",channel:Y="general",callback:H=(L)=>console.log(L)})=>{let L=v(()=>{if(!$)return"";let W=`${$?.key}=${$?.operator}`;if($?.operator==="in")return`${W}.(${$?.value.toString()})`;return`${W}.${$?.value}`},[$]),N=v(()=>{if(!L)return{event:G,schema:Z,table:V};return{event:G,schema:Z,table:V,filter:L}},[G,Z,V,L]),z=j((W)=>{if(console.log("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"),console.log("\uD83D\uDD25 REALTIME EVENT RECEIVED FROM BACKEND"),console.log("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"),console.log("\uD83D\uDCCA Event Type:",W.eventType),console.log("\uD83D\uDCCB Table:",W.table),console.log("\uD83C\uDFF7️ Schema:",W.schema),console.log("⏰ Timestamp:",new Date(W.commit_timestamp).toLocaleString()),W.eventType==="INSERT")console.log("✅ INSERT - New Record:"),console.log(" → New Data:",W.new);else if(W.eventType==="UPDATE")console.log("\uD83D\uDD04 UPDATE - Record Modified:"),console.log(" → Old Data:",W.old),console.log(" → New Data:",W.new);else if(W.eventType==="DELETE")console.log("❌ DELETE - Record Removed:"),console.log(" → Old Data:",W.old);console.log("\uD83D\uDCE6 Full Payload:",W),console.log("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"),H(W)},[H]);f(()=>{console.log("\uD83D\uDD27 Setting up Supabase subscription:",{channel:Y,type:I,table:V,schema:Z,filter:L,configQuery:N});let W=x.channel(Y).on(I,N,z).subscribe((M)=>{if(console.log("\uD83D\uDCE1 Subscription status:",M),M==="SUBSCRIBED")console.log("✅ Successfully subscribed to channel:",Y),console.log("\uD83D\uDC42 Listening for events on table:",V),console.log("\uD83D\uDD0D Filter:",L||"No filter (all records)");else if(M==="CHANNEL_ERROR")console.error("❌ Subscription error on channel:",Y);else if(M==="TIMED_OUT")console.error("⏱️ Subscription timed out on channel:",Y);else if(M==="CLOSED")console.warn("\uD83D\uDD12 Channel closed:",Y)});return()=>{console.log("\uD83D\uDD0C Unsubscribing from channel:",Y),W.unsubscribe()}},[z,N,I,Y,V,Z,L])};return{useSupaSubscription:X,useSupaRealtime:({table:V,where:Z,channel:G="general",schema:$="public"})=>{let I=w(),Y=v(()=>Z?{[Z.operator]:{[Z.key]:Z.value}}:{},[Z]);console.log("\uD83D\uDD0D useSupaRealtime queryConfig:",Y),console.log("\uD83D\uDD0D useSupaRealtime where:",Z);let H=v(()=>{return[[V,"subscription"].join("_"),Y,void 0,void 0,"estimated",V,"*","estimated",{queryKey:["subscription"]},void 0,void 0]},[V,Y]);console.log("\uD83D\uDD0D useSupaRealtime QueryKey:",H);let L=J({table:V,schema:$,where:Y,options:{queryKey:["subscription"]},count:"estimated"});console.log("\uD83D\uDD0D useSupaRealtime query result:",L.data);let N=j((z)=>{console.log("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"),console.log("\uD83D\uDD25 REALTIME EVENT IN handleRealtimeEvent"),console.log("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"),console.log("\uD83D\uDCCA Event Type:",z.eventType),console.log("\uD83D\uDCE6 Payload:",z),console.log("\uD83D\uDD11 Current QueryKey:",H);let W=I.getQueryData(H);console.log("\uD83D\uDCBE Current Cache Data BEFORE update:",W);let R={[C.DELETE]:()=>{console.log("\uD83D\uDDD1️ Processing DELETE event"),I.setQueryData(H,(F)=>{if(console.log(" → oldData in DELETE:",F),!F)return console.log(" ⚠️ No oldData, returning null"),F;let B=Array.isArray(F.payload)?F.payload.filter((P)=>P.id!==z.old.id):[],A={count:B.length,payload:B};return console.log(" ✅ DELETE result:",A),A})},[C.INSERT]:()=>{console.log("➕ Processing INSERT event"),I.setQueryData(H,(F)=>{if(console.log(" → oldData in INSERT:",F),!F){let P={count:1,payload:[z.new]};return console.log(" ✅ INSERT result (no oldData):",P),P}let B=Array.isArray(F.payload)?[...F.payload,z.new]:[z.new],A={count:B.length,payload:B};return console.log(" ✅ INSERT result:",A),A})},[C.UPDATE]:()=>{console.log("\uD83D\uDD04 Processing UPDATE event"),console.log(" → payload.old:",z.old),console.log(" → payload.new:",z.new),console.log(" → payload.new.state:",z.new.state),console.log(" → payload.new.state is Array?",Array.isArray(z.new.state)),console.log(" → payload.new.state length:",z.new.state?.length),I.setQueryData(H,(F)=>{if(console.log(" → oldData in UPDATE:",F),console.log(" → oldData.payload type:",typeof F?.payload),console.log(" → oldData.payload length:",F?.payload?.length),!F)return console.log(" ⚠️ No oldData, returning null"),F;let B=Array.isArray(F.payload)?F.payload.map((P)=>{if(P.id===z.old.id)return console.log(" \uD83C\uDFAF Found matching record, updating:",P.id),console.log(" \uD83C\uDFAF Old record:",P),console.log(" \uD83C\uDFAF New record:",z.new),z.new;return P}):[],A={count:B.length,payload:B};return console.log(" ✅ UPDATE result:",A),console.log(" ✅ Updated record state:",A.payload?.[0]?.state),A})}}[z.eventType];if(R){console.log("✅ Handler found, executing..."),R();let F=I.getQueryData(H);console.log("\uD83D\uDCBE Cache Data AFTER update:",F),console.log("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━")}else console.log("❌ No handler found for event type:",z.eventType),console.log("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━")},[I,H]);return X({table:V,schema:$,event:"*",where:Z,type:"postgres_changes",channel:G,callback:N}),L}}};var zx=(x)=>{let J=()=>p(()=>x,[]),X=()=>{let G=g();return Q(()=>{let{data:{subscription:$}}=x.auth.onAuthStateChange(()=>{G.invalidateQueries({queryKey:["supa_session"]})});return()=>$.unsubscribe()},[G]),b({queryKey:["supa_session"],initialData:null,queryFn:async()=>{let{data:$,error:I}=await x.auth.getSession();if(I)throw I;return $.session}})},U=D(x),V=E(x,U.useSupaQuery);return{useSupabase:J,useSupaSession:X,getSupaQueryName:({table:G,queryKey:$})=>T({table:G,queryKey:$}),...U,...V}};export{zx as createSupabaseTools,D as createSupabaseQuery,_ as QueryBuilder};