@supabase-kit/react
Version:
> Hooks by management data from supabase and fetch data by react.
876 lines (867 loc) • 31.8 kB
JavaScript
'use strict';
var reactQuery = require('@tanstack/react-query');
var react = require('react');
var supabaseJs = require('@supabase/supabase-js');
function _arrayLikeToArray(r, a) {
(null == a || a > r.length) && (a = r.length);
for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e];
return n;
}
function asyncGeneratorStep(n, t, e, r, o, a, c) {
try {
var i = n[a](c),
u = i.value;
} catch (n) {
return void e(n);
}
i.done ? t(u) : Promise.resolve(u).then(r, o);
}
function _asyncToGenerator(n) {
return function () {
var t = this,
e = arguments;
return new Promise(function (r, o) {
var a = n.apply(t, e);
function _next(n) {
asyncGeneratorStep(a, r, o, _next, _throw, "next", n);
}
function _throw(n) {
asyncGeneratorStep(a, r, o, _next, _throw, "throw", n);
}
_next(void 0);
});
};
}
function _createForOfIteratorHelperLoose(r, e) {
var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"];
if (t) return (t = t.call(r)).next.bind(t);
if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) {
t && (r = t);
var o = 0;
return function () {
return o >= r.length ? {
done: !0
} : {
done: !1,
value: r[o++]
};
};
}
throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _extends() {
return _extends = Object.assign ? Object.assign.bind() : function (n) {
for (var e = 1; e < arguments.length; e++) {
var t = arguments[e];
for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]);
}
return n;
}, _extends.apply(null, arguments);
}
function _objectWithoutPropertiesLoose(r, e) {
if (null == r) return {};
var t = {};
for (var n in r) if ({}.hasOwnProperty.call(r, n)) {
if (e.includes(n)) continue;
t[n] = r[n];
}
return t;
}
function _regeneratorRuntime() {
_regeneratorRuntime = function () {
return e;
};
var t,
e = {},
r = Object.prototype,
n = r.hasOwnProperty,
o = Object.defineProperty || function (t, e, r) {
t[e] = r.value;
},
i = "function" == typeof Symbol ? Symbol : {},
a = i.iterator || "@@iterator",
c = i.asyncIterator || "@@asyncIterator",
u = i.toStringTag || "@@toStringTag";
function define(t, e, r) {
return Object.defineProperty(t, e, {
value: r,
enumerable: !0,
configurable: !0,
writable: !0
}), t[e];
}
try {
define({}, "");
} catch (t) {
define = function (t, e, r) {
return t[e] = r;
};
}
function wrap(t, e, r, n) {
var i = e && e.prototype instanceof Generator ? e : Generator,
a = Object.create(i.prototype),
c = new Context(n || []);
return o(a, "_invoke", {
value: makeInvokeMethod(t, r, c)
}), a;
}
function tryCatch(t, e, r) {
try {
return {
type: "normal",
arg: t.call(e, r)
};
} catch (t) {
return {
type: "throw",
arg: t
};
}
}
e.wrap = wrap;
var h = "suspendedStart",
l = "suspendedYield",
f = "executing",
s = "completed",
y = {};
function Generator() {}
function GeneratorFunction() {}
function GeneratorFunctionPrototype() {}
var p = {};
define(p, a, function () {
return this;
});
var d = Object.getPrototypeOf,
v = d && d(d(values([])));
v && v !== r && n.call(v, a) && (p = v);
var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p);
function defineIteratorMethods(t) {
["next", "throw", "return"].forEach(function (e) {
define(t, e, function (t) {
return this._invoke(e, t);
});
});
}
function AsyncIterator(t, e) {
function invoke(r, o, i, a) {
var c = tryCatch(t[r], t, o);
if ("throw" !== c.type) {
var u = c.arg,
h = u.value;
return h && "object" == typeof h && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) {
invoke("next", t, i, a);
}, function (t) {
invoke("throw", t, i, a);
}) : e.resolve(h).then(function (t) {
u.value = t, i(u);
}, function (t) {
return invoke("throw", t, i, a);
});
}
a(c.arg);
}
var r;
o(this, "_invoke", {
value: function (t, n) {
function callInvokeWithMethodAndArg() {
return new e(function (e, r) {
invoke(t, n, e, r);
});
}
return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg();
}
});
}
function makeInvokeMethod(e, r, n) {
var o = h;
return function (i, a) {
if (o === f) throw Error("Generator is already running");
if (o === s) {
if ("throw" === i) throw a;
return {
value: t,
done: !0
};
}
for (n.method = i, n.arg = a;;) {
var c = n.delegate;
if (c) {
var u = maybeInvokeDelegate(c, n);
if (u) {
if (u === y) continue;
return u;
}
}
if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) {
if (o === h) throw o = s, n.arg;
n.dispatchException(n.arg);
} else "return" === n.method && n.abrupt("return", n.arg);
o = f;
var p = tryCatch(e, r, n);
if ("normal" === p.type) {
if (o = n.done ? s : l, p.arg === y) continue;
return {
value: p.arg,
done: n.done
};
}
"throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg);
}
};
}
function maybeInvokeDelegate(e, r) {
var n = r.method,
o = e.iterator[n];
if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y;
var i = tryCatch(o, e.iterator, r.arg);
if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y;
var a = i.arg;
return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y);
}
function pushTryEntry(t) {
var e = {
tryLoc: t[0]
};
1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e);
}
function resetTryEntry(t) {
var e = t.completion || {};
e.type = "normal", delete e.arg, t.completion = e;
}
function Context(t) {
this.tryEntries = [{
tryLoc: "root"
}], t.forEach(pushTryEntry, this), this.reset(!0);
}
function values(e) {
if (e || "" === e) {
var r = e[a];
if (r) return r.call(e);
if ("function" == typeof e.next) return e;
if (!isNaN(e.length)) {
var o = -1,
i = function next() {
for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next;
return next.value = t, next.done = !0, next;
};
return i.next = i;
}
}
throw new TypeError(typeof e + " is not iterable");
}
return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", {
value: GeneratorFunctionPrototype,
configurable: !0
}), o(GeneratorFunctionPrototype, "constructor", {
value: GeneratorFunction,
configurable: !0
}), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) {
var e = "function" == typeof t && t.constructor;
return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name));
}, e.mark = function (t) {
return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t;
}, e.awrap = function (t) {
return {
__await: t
};
}, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () {
return this;
}), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) {
void 0 === i && (i = Promise);
var a = new AsyncIterator(wrap(t, r, n, o), i);
return e.isGeneratorFunction(r) ? a : a.next().then(function (t) {
return t.done ? t.value : a.next();
});
}, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () {
return this;
}), define(g, "toString", function () {
return "[object Generator]";
}), e.keys = function (t) {
var e = Object(t),
r = [];
for (var n in e) r.push(n);
return r.reverse(), function next() {
for (; r.length;) {
var t = r.pop();
if (t in e) return next.value = t, next.done = !1, next;
}
return next.done = !0, next;
};
}, e.values = values, Context.prototype = {
constructor: Context,
reset: function (e) {
if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t);
},
stop: function () {
this.done = !0;
var t = this.tryEntries[0].completion;
if ("throw" === t.type) throw t.arg;
return this.rval;
},
dispatchException: function (e) {
if (this.done) throw e;
var r = this;
function handle(n, o) {
return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o;
}
for (var o = this.tryEntries.length - 1; o >= 0; --o) {
var i = this.tryEntries[o],
a = i.completion;
if ("root" === i.tryLoc) return handle("end");
if (i.tryLoc <= this.prev) {
var c = n.call(i, "catchLoc"),
u = n.call(i, "finallyLoc");
if (c && u) {
if (this.prev < i.catchLoc) return handle(i.catchLoc, !0);
if (this.prev < i.finallyLoc) return handle(i.finallyLoc);
} else if (c) {
if (this.prev < i.catchLoc) return handle(i.catchLoc, !0);
} else {
if (!u) throw Error("try statement without catch or finally");
if (this.prev < i.finallyLoc) return handle(i.finallyLoc);
}
}
}
},
abrupt: function (t, e) {
for (var r = this.tryEntries.length - 1; r >= 0; --r) {
var o = this.tryEntries[r];
if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) {
var i = o;
break;
}
}
i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null);
var a = i ? i.completion : {};
return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a);
},
complete: function (t, e) {
if ("throw" === t.type) throw t.arg;
return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y;
},
finish: function (t) {
for (var e = this.tryEntries.length - 1; e >= 0; --e) {
var r = this.tryEntries[e];
if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y;
}
},
catch: function (t) {
for (var e = this.tryEntries.length - 1; e >= 0; --e) {
var r = this.tryEntries[e];
if (r.tryLoc === t) {
var n = r.completion;
if ("throw" === n.type) {
var o = n.arg;
resetTryEntry(r);
}
return o;
}
}
throw Error("illegal catch attempt");
},
delegateYield: function (e, r, n) {
return this.delegate = {
iterator: values(e),
resultName: r,
nextLoc: n
}, "next" === this.method && (this.arg = t), y;
}
}, e;
}
function _unsupportedIterableToArray(r, a) {
if (r) {
if ("string" == typeof r) return _arrayLikeToArray(r, a);
var t = {}.toString.call(r).slice(8, -1);
return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0;
}
}
var GetSupaQueryName = function GetSupaQueryName(_ref) {
var table = _ref.table,
queryKey = _ref.queryKey;
return [table].concat(queryKey).join('_');
};
var _excluded$1 = ["where"];
var objMatchBuild = {
match: function match(Query, _match) {
if (_match === void 0) {
_match = {};
}
return Query.match(_match);
},
or: function or(Query, ors) {
if (ors === void 0) {
ors = [];
}
for (var _iterator = _createForOfIteratorHelperLoose(ors), _step; !(_step = _iterator()).done;) {
var _or = _step.value;
Query = Query.or(_or);
}
return Query;
},
filter: function filter(Query, _filter) {
if (_filter === void 0) {
_filter = {};
}
for (var _i = 0, _Object$entries = Object.entries(_filter); _i < _Object$entries.length; _i++) {
var _Object$entries$_i = _Object$entries[_i],
k = _Object$entries$_i[0],
v = _Object$entries$_i[1];
Query.filter.apply(Query, [k].concat(v));
}
return Query;
},
not: function not(Query, textSearch) {
if (textSearch === void 0) {
textSearch = {};
}
for (var _i2 = 0, _Object$keys = Object.keys(textSearch); _i2 < _Object$keys.length; _i2++) {
var k = _Object$keys[_i2];
var _textSearch$k =
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
textSearch[k],
text = _textSearch$k.text,
options = _textSearch$k.options;
Query = Query.textSearch(k, text, options);
}
return Query;
},
limit: function limit(Query, _limit) {
return Query.limit(_limit);
},
single: function single(Query) {
return Query = Query.single();
},
maybeSingle: function maybeSingle(Query) {
return Query.maybeSingle();
},
csv: function csv(Query) {
return Query.csv();
},
explain: function explain(Query, _explain) {
if (_explain === void 0) {
_explain = {};
}
return Query.explain(_explain);
},
order: function order(Query, _order) {
for (var _i3 = 0, _Object$entries2 = Object.entries(_order); _i3 < _Object$entries2.length; _i3++) {
var _Object$entries2$_i = _Object$entries2[_i3],
k = _Object$entries2$_i[0],
v = _Object$entries2$_i[1];
Query = Query.order(k, v);
}
return Query;
},
range: function range(Query, ranges) {
var onRange = function onRange(range) {
return Query.range(range.from, range.to, range.options);
};
if (!Array.isArray(ranges)) return onRange(ranges);
for (var _iterator2 = _createForOfIteratorHelperLoose(ranges), _step2; !(_step2 = _iterator2()).done;) {
var range = _step2.value;
Query = onRange(range);
}
return Query;
}
};
/**
* Enhances a Supabase query with various filtering, ordering, and formatting options.
*
* @template D - The database schema type.
* @template SchemaName - The schema name within the database.
* @template Schema - The specific schema definition.
*
* @param {ConfigObj<D>} param0 - Configuration object containing filtering and other options.
* @param {PostgrestFilterBuilder<Schema, any, any>} Query - The initial Postgrest query builder object.
*
* @returns {PostgrestFilterBuilder<Schema, any, any>} - The enhanced Postgrest query builder object with applied configurations.
*/
var QueryBuilder = function QueryBuilder(_ref, Query) {
var _ref$where = _ref.where,
where = _ref$where === void 0 ? {} : _ref$where,
options = _objectWithoutPropertiesLoose(_ref, _excluded$1);
var base = _extends({}, where, options);
var where_keys = ['eq', 'neq', 'in', 'is', 'lt', 'lte', 'gt', 'gte', 'like', 'ilike', 'contains', 'containedBy', 'rangeGt', 'rangeGte', 'rangeLt', 'rangeLte', 'rangeAdjacent', 'contains', 'containedBy', 'rangeGt', 'rangeGte', 'rangeLt', 'rangeLte', 'rangeAdjacent', 'overlaps'];
for (var _i4 = 0, _Object$entries3 = Object.entries(base); _i4 < _Object$entries3.length; _i4++) {
var _Object$entries3$_i = _Object$entries3[_i4],
kp = _Object$entries3$_i[0],
vQ = _Object$entries3$_i[1];
var k = kp;
var method = objMatchBuild[k];
if (method) {
Query = method(Query, vQ);
continue;
}
if (!where_keys.includes(k)) continue;
for (var _i5 = 0, _Object$entries4 = Object.entries(vQ); _i5 < _Object$entries4.length; _i5++) {
var _Object$entries4$_i = _Object$entries4[_i5],
K = _Object$entries4$_i[0],
v = _Object$entries4$_i[1];
Query = Query[k](K, v);
}
}
return Query;
};
var _excluded = ["table", "column", "count", "options", "single", "enabled"],
_excluded2 = ["queryKey"],
_excluded3 = ["table", "column", "options", "enabled", "count"],
_excluded4 = ["initialData", "queryKey"];
// Sobrecargas de la función useSupaQuery
var createSupabaseQuery = function createSupabaseQuery(client) {
function useSupaQuery(_ref) {
var table = _ref.table,
_ref$column = _ref.column,
column = _ref$column === void 0 ? '*' : _ref$column,
count = _ref.count,
_ref$options = _ref.options,
options = _ref$options === void 0 ? {} : _ref$options,
single = _ref.single,
enabled = _ref.enabled,
configObj = _objectWithoutPropertiesLoose(_ref, _excluded);
var fetchData = /*#__PURE__*/function () {
var _ref2 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee(signal) {
var QueryBase, QueryFn, _yield$QueryFn$abortS, data, error, rowCount;
return _regeneratorRuntime().wrap(function _callee$(_context) {
while (1) switch (_context.prev = _context.next) {
case 0:
QueryBase = client.from(table).select(column, {
count: count
});
QueryFn = QueryBuilder(configObj, QueryBase);
_context.next = 4;
return QueryFn.abortSignal(signal);
case 4:
_yield$QueryFn$abortS = _context.sent;
data = _yield$QueryFn$abortS.data;
error = _yield$QueryFn$abortS.error;
rowCount = _yield$QueryFn$abortS.count;
if (!error) {
_context.next = 10;
break;
}
throw error;
case 10:
return _context.abrupt("return", {
count: rowCount != null ? rowCount : 0,
payload: single ? data != null ? data : {} : data != null ? data : []
});
case 11:
case "end":
return _context.stop();
}
}, _callee);
}));
return function fetchData(_x) {
return _ref2.apply(this, arguments);
};
}();
var _options$queryKey = options.queryKey,
queryKey = _options$queryKey === void 0 ? [] : _options$queryKey,
optionsHooks = _objectWithoutPropertiesLoose(options, _excluded2);
var initQueryKey = GetSupaQueryName({
table: table,
queryKey: queryKey
});
return reactQuery.useQuery(_extends({
queryKey: [initQueryKey, configObj.where, configObj.limit, single, count, table, column, count, options, single, enabled],
queryFn: function queryFn(_ref3) {
var signal = _ref3.signal;
return fetchData(signal);
},
enabled: enabled
}, optionsHooks));
}
/**
* React Query hook for fetching data from a Supabase table with infinite scroll.
*
* @param {string} table - The table to fetch data from.
* @param {string} [column='*'] - The column(s) to fetch. Defaults to '*'.
* @param {Object} [options={}] - Options for the hook. See {@link https://react-query.tanstack.com/docs/api#useinfinitequery}
* @param {boolean} [enabled=true] - Whether the hook is enabled.
* @param {'exact'|'planned'|'estimated'} [count='exact'] - The type of count to fetch. See {@link https://supabase.io/docs/reference/postgrest/count}
* @param {Object} [configObj={}] - Additional configuration options for the query. See {@link https://supabase.io/docs/reference/postgrest/filters}
* @returns {UseInfiniteQueryResult<SupabaseQueryResult<V>, PostgrestError>} - The result of the query.
*/
var useSupaInfiniteQuery = function useSupaInfiniteQuery(_ref4) {
var table = _ref4.table,
_ref4$column = _ref4.column,
column = _ref4$column === void 0 ? '*' : _ref4$column,
options = _ref4.options,
enabled = _ref4.enabled,
_ref4$count = _ref4.count,
count = _ref4$count === void 0 ? 'exact' : _ref4$count,
configObj = _objectWithoutPropertiesLoose(_ref4, _excluded3);
var fetchData = /*#__PURE__*/function () {
var _ref5 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee2(signal) {
var QueryBase, QueryFn, _yield$QueryFn$abortS2, data, error, rowCount;
return _regeneratorRuntime().wrap(function _callee2$(_context2) {
while (1) switch (_context2.prev = _context2.next) {
case 0:
QueryBase = client.from(table).select(column, {
count: count
});
QueryFn = QueryBuilder(configObj, QueryBase);
_context2.next = 4;
return QueryFn.abortSignal(signal);
case 4:
_yield$QueryFn$abortS2 = _context2.sent;
data = _yield$QueryFn$abortS2.data;
error = _yield$QueryFn$abortS2.error;
rowCount = _yield$QueryFn$abortS2.count;
if (!error) {
_context2.next = 10;
break;
}
throw error;
case 10:
return _context2.abrupt("return", {
count: rowCount != null ? rowCount : 0,
payload: data != null ? data : []
});
case 11:
case "end":
return _context2.stop();
}
}, _callee2);
}));
return function fetchData(_x2) {
return _ref5.apply(this, arguments);
};
}();
var _options$queryKey2 = options.queryKey,
queryKey = _options$queryKey2 === void 0 ? [] : _options$queryKey2,
optionsHook = _objectWithoutPropertiesLoose(options, _excluded4);
var initQueryKey = GetSupaQueryName({
table: table,
queryKey: ['infinite'].concat(queryKey)
});
return reactQuery.useInfiniteQuery(_extends({
queryKey: [initQueryKey, configObj.where, configObj.limit],
queryFn: function queryFn(_ref6) {
var signal = _ref6.signal;
return fetchData(signal);
},
enabled: enabled
}, optionsHook));
};
return {
useSupaInfiniteQuery: useSupaInfiniteQuery,
useSupaQuery: useSupaQuery,
QueryBuilder: QueryBuilder
};
};
var createSupabaseSubscription = function createSupabaseSubscription(client, useQuery) {
/**
* Custom hook to create a Supabase subscription with specified configurations.
*
* @template D - Database schema type.
*
* @param {Object} config - Configuration object for the subscription.
* @param {string} config.table - The name of the table to subscribe to.
* @param {string} [config.schema='public'] - The database schema to use.
* @param {string} [config.event='*'] - Event type to listen for (e.g., INSERT, UPDATE, DELETE).
* @param {Object} [config.where] - Filter object to specify conditions for events.
* @param {string} [config.type='postgres_changes'] - Type of event to listen for.
* @param {string} [config.channel='general'] - Channel name for the subscription.
* @param {Function} [config.callback=(payload) => console.log(payload)] - Callback function to handle subscription payloads.
*
* @returns {void}
*
* This hook sets up a Supabase subscription based on the provided configuration.
* It automatically unsubscribes when the component is unmounted or the dependencies change.
*/
var useSupaSubscription = function useSupaSubscription(_ref) {
var table = _ref.table,
_ref$schema = _ref.schema,
schema = _ref$schema === void 0 ? 'public' : _ref$schema,
_ref$event = _ref.event,
event = _ref$event === void 0 ? '*' : _ref$event,
where = _ref.where,
_ref$type = _ref.type,
type = _ref$type === void 0 ? 'postgres_changes' : _ref$type,
_ref$channel = _ref.channel,
channel = _ref$channel === void 0 ? 'general' : _ref$channel,
_ref$callback = _ref.callback,
callback = _ref$callback === void 0 ? function (payload) {
return console.log(payload);
} : _ref$callback;
var filter = react.useMemo(function () {
if (!where) return '';
var base = (where == null ? void 0 : where.key) + "=" + (where == null ? void 0 : where.operator);
if ((where == null ? void 0 : where.operator) === 'in') return base + ".(" + (where == null ? void 0 : where.value.toString()) + ")";
return base + "." + (where == null ? void 0 : where.value);
}, [where]);
var configQuery = react.useMemo(function () {
if (!filter) return {
event: event,
schema: schema,
table: table
};
return {
event: event,
schema: schema,
table: table,
filter: filter
};
}, [event, schema, table, filter]);
react.useEffect(function () {
var subscription = client.channel(channel).on(type, configQuery, callback).subscribe();
return function () {
subscription.unsubscribe();
};
}, [callback, configQuery, type, channel]);
};
/**
* Use a subscription to listen to a table in real time.
* @param {Object} props - Options for the subscription.
* @param {string} props.table - The table to listen to.
* @param {Object} props.where - A filter to apply to the subscription.
* @param {string} [props.channel=general] - The channel to subscribe to.
* @returns {UseQueryResult} The result of the subscription.
*/
var useSupaRealtime = function useSupaRealtime(_ref2) {
var table = _ref2.table,
where = _ref2.where,
_ref2$channel = _ref2.channel,
channel = _ref2$channel === void 0 ? 'general' : _ref2$channel;
var queryClient = reactQuery.useQueryClient();
var queryConfig = react.useMemo(function () {
var _where$operator, _ref3;
return where ? (_ref3 = {}, _ref3[where.operator] = (_where$operator = {}, _where$operator[where.key] = where.value, _where$operator), _ref3) : {};
}, [where]);
var QueryKey = [[table, 'subscription'].join('_'), queryConfig, null,
// limit
null,
// single
'estimated' // count
];
var query = useQuery({
table: table,
where: queryConfig,
options: {
queryKey: ['subscription']
},
count: 'estimated'
});
useSupaSubscription({
table: table,
schema: 'public',
event: '*',
where: where,
type: 'postgres_changes',
channel: channel,
callback: function callback(payload) {
var _eventMatch;
var eventMatch = (_eventMatch = {}, _eventMatch[supabaseJs.REALTIME_POSTGRES_CHANGES_LISTEN_EVENT.DELETE] = function () {
queryClient.setQueryData(QueryKey, function (oldData) {
var payload = oldData.payload.filter(function (d) {
return d.id !== payload.old.id;
});
var count = payload.length;
return {
count: count,
payload: payload
};
});
}, _eventMatch[supabaseJs.REALTIME_POSTGRES_CHANGES_LISTEN_EVENT.INSERT] = function () {
queryClient.setQueryData(QueryKey, function (oldData) {
var newPayload = [].concat(oldData.payload, [payload["new"]]);
var count = newPayload.length;
return {
count: count,
payload: newPayload
};
});
}, _eventMatch[supabaseJs.REALTIME_POSTGRES_CHANGES_LISTEN_EVENT.UPDATE] = function () {
queryClient.setQueryData(QueryKey, function (oldData) {
var payload = oldData.payload.map(function (d) {
if (d.id === payload.old.id) return payload["new"];
return d;
});
var count = payload.length;
return {
count: count,
payload: payload
};
});
}, _eventMatch);
eventMatch[payload.eventType]();
}
});
return query;
};
return {
useSupaSubscription: useSupaSubscription,
useSupaRealtime: useSupaRealtime
};
};
var createSupabaseTools = function createSupabaseTools(client) {
var useSupabase = function useSupabase() {
return react.useMemo(function () {
return client;
}, []);
};
/**
* Hook to get the user session.
* @returns The user session.
*
* The query key is `['session', client]`.
* The query function is `async () => client.auth.getSession()`.
* The initial data is `null`.
*/
var useSupaSession = function useSupaSession() {
return reactQuery.useQuery({
queryKey: ['supa_session', client],
initialData: null,
queryFn: function () {
var _queryFn = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee() {
var _yield$client$auth$ge, data, error;
return _regeneratorRuntime().wrap(function _callee$(_context) {
while (1) switch (_context.prev = _context.next) {
case 0:
_context.next = 2;
return client.auth.getSession();
case 2:
_yield$client$auth$ge = _context.sent;
data = _yield$client$auth$ge.data;
error = _yield$client$auth$ge.error;
if (!error) {
_context.next = 7;
break;
}
throw error;
case 7:
return _context.abrupt("return", data.session);
case 8:
case "end":
return _context.stop();
}
}, _callee);
}));
function queryFn() {
return _queryFn.apply(this, arguments);
}
return queryFn;
}()
});
};
var SupabaseQuery = createSupabaseQuery(client);
var SupabaseSubscription = createSupabaseSubscription(client, SupabaseQuery.useSupaQuery);
var getSupaQueryName = function getSupaQueryName(_ref) {
var table = _ref.table,
queryKey = _ref.queryKey;
return GetSupaQueryName({
table: table,
queryKey: queryKey
});
};
return _extends({
useSupabase: useSupabase,
useSupaSession: useSupaSession,
getSupaQueryName: getSupaQueryName
}, SupabaseQuery, SupabaseSubscription);
};
exports.QueryBuilder = QueryBuilder;
exports.createSupabaseQuery = createSupabaseQuery;
exports.createSupabaseTools = createSupabaseTools;
//# sourceMappingURL=react.cjs.development.js.map