@cytools/vue-query
Version:
Introducing elegant way of making api requests and asynchronous functions with the composition api in Vue
772 lines (744 loc) • 38.1 kB
JavaScript
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('vue-demi'), require('lodash')) :
typeof define === 'function' && define.amd ? define(['exports', 'vue-demi', 'lodash'], factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.VueQuery = {}, global['vue-demi'], global.lodash));
}(this, (function (exports, vueDemi, lodash) { 'use strict';
/*! *****************************************************************************
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
/* global Reflect, Promise */
var extendStatics = function(d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
function __extends(d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}
var __assign = function() {
__assign = Object.assign || function __assign(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
function __awaiter(thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
}
function __generator(thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
}
function __values(o) {
var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
if (m) return m.call(o);
if (o && typeof o.length === "number") return {
next: function () {
if (o && i >= o.length) o = void 0;
return { value: o && o[i++], done: !o };
}
};
throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
}
function __read(o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
}
catch (error) { e = { error: error }; }
finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
}
finally { if (e) throw e.error; }
}
return ar;
}
function __spread() {
for (var ar = [], i = 0; i < arguments.length; i++)
ar = ar.concat(__read(arguments[i]));
return ar;
}
var QueryStatus;
(function (QueryStatus) {
QueryStatus["IDLE"] = "idle";
QueryStatus["ERROR"] = "error";
QueryStatus["LOADING"] = "loading";
QueryStatus["SUCCESS"] = "success";
})(QueryStatus || (QueryStatus = {}));
exports.queryDataClone = lodash.cloneDeep;
var changeQueryDataCloneMethod = function (newCloneFunction) { return exports.queryDataClone = newCloneFunction; };
var Query = /** @class */ (function () {
function Query(_a) {
var _b = _a === void 0 ? {} : _a, _c = _b.data, data = _c === void 0 ? null : _c, _d = _b.error, error = _d === void 0 ? null : _d, _e = _b.isFetching, isFetching = _e === void 0 ? false : _e, _f = _b.status, status = _f === void 0 ? QueryStatus.IDLE : _f;
this.queryData = vueDemi.reactive({
value: {
data: exports.queryDataClone(data),
error: error,
status: status,
isFetching: isFetching,
},
});
}
Query.prototype.update = function (queryData) {
this.queryData.value = __assign(__assign(__assign({}, this.queryData.value), queryData), { data: exports.queryDataClone(queryData.data || this.queryData.value.data) });
return this;
};
Query.prototype.updateData = function (callback) {
return this.update({
data: callback(this.data),
});
};
Object.defineProperty(Query.prototype, "data", {
get: function () {
return this.queryData.value.data;
},
enumerable: false,
configurable: true
});
Object.defineProperty(Query.prototype, "status", {
get: function () {
return this.queryData.value.status;
},
enumerable: false,
configurable: true
});
Object.defineProperty(Query.prototype, "error", {
get: function () {
return this.queryData.value.error;
},
enumerable: false,
configurable: true
});
Object.defineProperty(Query.prototype, "isIdle", {
get: function () {
return this.queryData.value.status === QueryStatus.IDLE;
},
enumerable: false,
configurable: true
});
Object.defineProperty(Query.prototype, "isError", {
get: function () {
return this.queryData.value.status === QueryStatus.ERROR;
},
enumerable: false,
configurable: true
});
Object.defineProperty(Query.prototype, "isLoading", {
get: function () {
return this.queryData.value.status === QueryStatus.LOADING;
},
enumerable: false,
configurable: true
});
Object.defineProperty(Query.prototype, "isSuccess", {
get: function () {
return this.queryData.value.status === QueryStatus.SUCCESS || this.queryData.value.data;
},
enumerable: false,
configurable: true
});
Object.defineProperty(Query.prototype, "isFetching", {
get: function () {
return this.queryData.value.isFetching;
},
enumerable: false,
configurable: true
});
return Query;
}());
/**
* External dependencies.
*/
var QueryClient = /** @class */ (function () {
function QueryClient(config) {
this.cache = config.cache;
}
QueryClient.prototype.addQuery = function (key, queryData) {
key = this.convertKey(key);
var query = this.getQuery(key);
if (query.value) {
return query;
}
this.cache.put(key, new Query(queryData));
return this.getQuery(key);
};
QueryClient.prototype.removeQuery = function (key) {
this.cache.remove(this.convertKey(key));
return this;
};
QueryClient.prototype.getQuery = function (key) {
return this.cache.get(this.convertKey(key));
};
QueryClient.prototype.getQueriesWithStartingKey = function (key) {
var _this = this;
var convertedKey = this.convertKey(key);
return vueDemi.computed(function () {
return _this.cache.getCacheKeys()
.map(function (queryCacheKey) {
if (queryCacheKey.includes(convertedKey)) {
return { key: queryCacheKey, query: _this.getQuery(queryCacheKey).value };
}
return null;
})
.filter(function (data) { return data; });
});
};
QueryClient.prototype.updateQueryDataForQueriesWithStartingKey = function (key, callback) {
this.getQueriesWithStartingKey(key)
.value
.forEach(function (query) { return query.query.updateData(callback); });
};
QueryClient.prototype.reset = function () {
return this.cache.clear();
};
QueryClient.prototype.convertKey = function (key) {
if (Array.isArray(key)) {
return JSON.stringify(key);
}
return key;
};
return QueryClient;
}());
var Cache = /** @class */ (function () {
function Cache() {
}
return Cache;
}());
var InMemoryCache = /** @class */ (function (_super) {
__extends(InMemoryCache, _super);
function InMemoryCache(initialData) {
if (initialData === void 0) { initialData = {}; }
var _this = _super.call(this) || this;
_this.cache = vueDemi.reactive({ value: initialData });
return _this;
}
InMemoryCache.prototype.put = function (key, data) {
this.updateCache(key, data);
return this;
};
InMemoryCache.prototype.get = function (key) {
var _this = this;
return vueDemi.computed(function () { return _this.cache.value[key] || null; });
};
InMemoryCache.prototype.remove = function (key) {
this.put(key, null);
return this;
};
InMemoryCache.prototype.count = function () {
var _this = this;
return Object.keys(this.cache.value).reduce(function (total, key) { return _this.cache.value[key] ? ++total : total; }, 0);
};
InMemoryCache.prototype.clear = function () {
this.cache.value = {};
return this;
};
InMemoryCache.prototype.getCacheKeys = function () {
return Object.keys(this.cache.value);
};
InMemoryCache.prototype.updateCache = function (key, data) {
var _a;
this.cache.value = __assign(__assign({}, this.cache.value), (_a = {}, _a[key] = data, _a));
};
return InMemoryCache;
}(Cache));
var initializedQueryClient = null;
function useQueryClient() {
initializedQueryClient = initializedQueryClient
|| new QueryClient({ cache: new InMemoryCache() });
var queryClient = initializedQueryClient;
return {
queryClient: queryClient,
};
}
var startTimeout = function (time) {
var timeoutId = null;
var promise = new Promise(function (resolve) {
timeoutId = setTimeout(resolve, time);
});
// @ts-ignore
promise.cancel = function () { return timeoutId && clearTimeout(timeoutId); };
return promise;
};
var containsAny = function (haystack, needles) {
var e_1, _a;
try {
for (var needles_1 = __values(needles), needles_1_1 = needles_1.next(); !needles_1_1.done; needles_1_1 = needles_1.next()) {
var needle = needles_1_1.value;
if (haystack.includes(needle)) {
return true;
}
}
}
catch (e_1_1) { e_1 = { error: e_1_1 }; }
finally {
try {
if (needles_1_1 && !needles_1_1.done && (_a = needles_1.return)) _a.call(needles_1);
}
finally { if (e_1) throw e_1.error; }
}
return false;
};
/**
* External dependencies.
*/
function useCurrentInstance() {
var instance = vueDemi.getCurrentInstance();
return lodash.get(instance, 'proxy', instance);
}
function useQueryKeyWatcher(_a) {
var _b = _a.key, key = _b === void 0 ? '' : _b, _c = _a.waitTime, waitTime = _c === void 0 ? 500 : _c, _d = _a.keysNotToWait, keysNotToWait = _d === void 0 ? [] : _d, _e = _a.keysNotToWatch, keysNotToWatch = _e === void 0 ? [] : _e, _f = _a.callback, callback = _f === void 0 ? function () { } : _f;
if (!key) {
throw new Error('No key has been provided!');
}
var watches = [];
var variables = [];
var instance = useCurrentInstance();
var initWatchersForReactiveVariables = function (keys) {
var e_1, _a, e_2, _b, e_3, _c;
if (!Array.isArray(keys)) {
return;
}
var foundKeysInObject = [];
var initializedVariableIndexes = [];
var onWatch = function (index) { return function (newValue) {
variables[index] = newValue;
callback();
}; };
try {
for (var keys_1 = __values(keys), keys_1_1 = keys_1.next(); !keys_1_1.done; keys_1_1 = keys_1.next()) {
var inKey = keys_1_1.value;
if (vueDemi.isRef(inKey)) {
initializedVariableIndexes.push({
index: variables.push(inKey.value) - 1,
reactiveValue: inKey,
});
}
else if (lodash.isObject(inKey)) {
try {
for (var _d = (e_2 = void 0, __values(Object.entries(inKey))), _e = _d.next(); !_e.done; _e = _d.next()) {
var _f = __read(_e.value, 2), objectKey = _f[0], data = _f[1];
if (keysNotToWatch.includes(objectKey)) {
continue;
}
if (!vueDemi.isRef(data)) {
initWatchersForReactiveVariables(data);
continue;
}
foundKeysInObject.push(objectKey);
initializedVariableIndexes.push({
index: variables.push(data.value) - 1,
reactiveValue: data,
});
}
}
catch (e_2_1) { e_2 = { error: e_2_1 }; }
finally {
try {
if (_e && !_e.done && (_b = _d.return)) _b.call(_d);
}
finally { if (e_2) throw e_2.error; }
}
}
}
}
catch (e_1_1) { e_1 = { error: e_1_1 }; }
finally {
try {
if (keys_1_1 && !keys_1_1.done && (_a = keys_1.return)) _a.call(keys_1);
}
finally { if (e_1) throw e_1.error; }
}
try {
for (var initializedVariableIndexes_1 = __values(initializedVariableIndexes), initializedVariableIndexes_1_1 = initializedVariableIndexes_1.next(); !initializedVariableIndexes_1_1.done; initializedVariableIndexes_1_1 = initializedVariableIndexes_1.next()) {
var indexData = initializedVariableIndexes_1_1.value;
if (waitTime > 0 && !containsAny(keysNotToWait, foundKeysInObject)) {
watches.push(vueDemi.watch(indexData.reactiveValue, lodash.debounce(onWatch(indexData.index), waitTime)));
continue;
}
watches.push(vueDemi.watch(indexData.reactiveValue, onWatch(indexData.index)));
}
}
catch (e_3_1) { e_3 = { error: e_3_1 }; }
finally {
try {
if (initializedVariableIndexes_1_1 && !initializedVariableIndexes_1_1.done && (_c = initializedVariableIndexes_1.return)) _c.call(initializedVariableIndexes_1);
}
finally { if (e_3) throw e_3.error; }
}
};
initWatchersForReactiveVariables(key);
if (instance) {
vueDemi.onUnmounted(function () {
watches.forEach(function (unwatch) { return unwatch(); });
watches = [];
variables = [];
});
}
return {
variables: variables,
};
}
function useQuery(key, callback, _a) {
var _this = this;
if (callback === void 0) { callback = null; }
var _b = _a === void 0 ? {} : _a, _c = _b.manual, manual = _c === void 0 ? false : _c, _d = _b.onError, onError = _d === void 0 ? function () { } : _d, _e = _b.keysNotToWait, keysNotToWait = _e === void 0 ? [] : _e, _f = _b.defaultData, defaultData = _f === void 0 ? null : _f, _g = _b.onSuccess, onSuccess = _g === void 0 ? function () { } : _g, _h = _b.keepPreviousData, keepPreviousData = _h === void 0 ? false : _h, _j = _b.timesToRetryOnError, timesToRetryOnError = _j === void 0 ? 3 : _j, _k = _b.onDataReceive, onDataReceive = _k === void 0 ? function () { } : _k, _l = _b.keyChangeRefetchWaitTime, keyChangeRefetchWaitTime = _l === void 0 ? 500 : _l, _m = _b.timeToWaitBeforeRetryingOnError, timeToWaitBeforeRetryingOnError = _m === void 0 ? 2000 : _m;
var initialized = false;
var data = vueDemi.ref(null);
var queryClient = useQueryClient().queryClient;
var query = vueDemi.reactive({ value: {} });
var fetchFromCacheOrRefetch = function (callbackVariables, canRefetch) {
if (callbackVariables === void 0) { callbackVariables = []; }
if (canRefetch === void 0) { canRefetch = true; }
return __awaiter(_this, void 0, void 0, function () {
var _a, _b, _c;
return __generator(this, function (_d) {
switch (_d.label) {
case 0:
query.value = queryClient.addQuery(key, { data: defaultData });
if (!((((_a = query.value) === null || _a === void 0 ? void 0 : _a.isIdle) || !((_b = query.value) === null || _b === void 0 ? void 0 : _b.data)) && callback)) return [3 /*break*/, 3];
if (!canRefetch) return [3 /*break*/, 2];
return [4 /*yield*/, refetch(callbackVariables)];
case 1:
_d.sent();
_d.label = 2;
case 2: return [3 /*break*/, 4];
case 3:
onDataReceive((_c = query.value) === null || _c === void 0 ? void 0 : _c.data);
initialized = true;
_d.label = 4;
case 4: return [2 /*return*/, query.value.data];
}
});
});
};
var initQuery = function () { return fetchFromCacheOrRefetch(variables, !manual); };
var variables = useQueryKeyWatcher({
key: key,
keysNotToWait: keysNotToWait,
callback: initQuery,
waitTime: keyChangeRefetchWaitTime,
}).variables;
var fetchData = function (callbackVariables, timesRetried) {
if (callbackVariables === void 0) { callbackVariables = []; }
if (timesRetried === void 0) { timesRetried = 0; }
return __awaiter(_this, void 0, void 0, function () {
var currentQuery, callbackResult, error, _a, _b, error_1;
var _c;
var _d;
return __generator(this, function (_e) {
switch (_e.label) {
case 0:
if (!callback) {
return [2 /*return*/];
}
if (((_d = query.value) === null || _d === void 0 ? void 0 : _d.isFetching) && timesRetried === 0) {
return [2 /*return*/];
}
currentQuery = query.value;
callbackVariables = callbackVariables.length ? callbackVariables : variables;
currentQuery.update({
isFetching: true,
});
callbackResult = callback.apply(void 0, __spread(callbackVariables));
// @ts-ignore
if (!(callbackResult instanceof Promise)) {
error = new Error('The provided callback doesn\'t return a promise!');
currentQuery.update({
error: error,
status: QueryStatus.ERROR,
});
onError(error);
return [2 /*return*/];
}
_e.label = 1;
case 1:
_e.trys.push([1, 3, 5, 6]);
_b = (_a = currentQuery).update;
_c = {};
return [4 /*yield*/, callbackResult];
case 2:
_b.apply(_a, [(_c.data = _e.sent(),
_c.status = QueryStatus.SUCCESS,
_c)]);
onSuccess(currentQuery.data);
onDataReceive(currentQuery.data);
return [3 /*break*/, 6];
case 3:
error_1 = _e.sent();
if (timesRetried >= timesToRetryOnError) {
currentQuery.update({
error: error_1,
status: QueryStatus.ERROR,
});
onError(error_1);
return [2 /*return*/];
}
return [4 /*yield*/, startTimeout(timeToWaitBeforeRetryingOnError)];
case 4:
_e.sent();
fetchData(callbackVariables, ++timesRetried);
return [3 /*break*/, 6];
case 5:
currentQuery.update({
isFetching: false,
});
return [7 /*endfinally*/];
case 6: return [2 /*return*/];
}
});
});
};
var refetch = function (callbackVariables) {
if (callbackVariables === void 0) { callbackVariables = []; }
return __awaiter(_this, void 0, void 0, function () {
var newData;
var _a;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
if (!keepPreviousData || !initialized) {
(_a = query.value) === null || _a === void 0 ? void 0 : _a.update({
status: QueryStatus.LOADING,
});
}
return [4 /*yield*/, fetchData(callbackVariables)];
case 1:
newData = _b.sent();
initialized = true;
return [2 /*return*/, newData];
}
});
});
};
initQuery();
vueDemi.watch(query, function (newQuery) {
var _a, _b;
if (!((_a = newQuery === null || newQuery === void 0 ? void 0 : newQuery.value) === null || _a === void 0 ? void 0 : _a.isSuccess)) {
return;
}
data.value = (_b = newQuery === null || newQuery === void 0 ? void 0 : newQuery.value) === null || _b === void 0 ? void 0 : _b.data;
}, {
immediate: true,
});
return {
refetch: refetch,
fetchFromCacheOrRefetch: fetchFromCacheOrRefetch,
updateQueryData: function (updateQueryDataCB) { var _a; return (_a = query.value) === null || _a === void 0 ? void 0 : _a.updateData(updateQueryDataCB); },
data: vueDemi.computed(function () { return data.value; }),
status: vueDemi.computed(function () { var _a; return (_a = query.value) === null || _a === void 0 ? void 0 : _a.status; }),
error: vueDemi.computed(function () { var _a; return (_a = query.value) === null || _a === void 0 ? void 0 : _a.error; }),
isIdle: vueDemi.computed(function () { var _a; return (_a = query.value) === null || _a === void 0 ? void 0 : _a.isIdle; }),
isError: vueDemi.computed(function () { var _a; return (_a = query.value) === null || _a === void 0 ? void 0 : _a.isError; }),
isLoading: vueDemi.computed(function () { var _a; return (_a = query.value) === null || _a === void 0 ? void 0 : _a.isLoading; }),
isSuccess: vueDemi.computed(function () { var _a; return (_a = query.value) === null || _a === void 0 ? void 0 : _a.isSuccess; }),
isFetching: vueDemi.computed(function () { var _a; return (_a = query.value) === null || _a === void 0 ? void 0 : _a.isFetching; }),
};
}
var MutationStatus;
(function (MutationStatus) {
MutationStatus["IDLE"] = "idle";
MutationStatus["ERROR"] = "error";
MutationStatus["LOADING"] = "loading";
MutationStatus["SUCCESS"] = "success";
})(MutationStatus || (MutationStatus = {}));
/* eslint-disable */
function useMutation(callback, _a) {
var _this = this;
var _b = _a === void 0 ? {} : _a, _c = _b.onError, onError = _c === void 0 ? function () { return null; } : _c, _d = _b.onSuccess, onSuccess = _d === void 0 ? function () { return null; } : _d, _e = _b.onMutate, onMutate = _e === void 0 ? function () { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) {
return [2 /*return*/, null];
}); }); } : _e;
var data = vueDemi.ref(null);
var error = vueDemi.ref(null);
var status = vueDemi.ref(MutationStatus.IDLE);
var context = vueDemi.ref(null);
var mutationResultReturn = function () { return ({
data: vueDemi.computed(function () { return data.value; }),
error: vueDemi.computed(function () { return error.value; }),
isIdle: vueDemi.computed(function () { return status.value === MutationStatus.IDLE; }),
isError: vueDemi.computed(function () { return status.value === MutationStatus.ERROR; }),
isSuccess: vueDemi.computed(function () { return status.value === MutationStatus.SUCCESS; }),
isLoading: vueDemi.computed(function () { return status.value === MutationStatus.LOADING; }),
}); };
var mutate = function () {
var variables = [];
for (var _i = 0; _i < arguments.length; _i++) {
variables[_i] = arguments[_i];
}
return __awaiter(_this, void 0, void 0, function () {
var _a, callbackResult, _b, e_1;
return __generator(this, function (_c) {
switch (_c.label) {
case 0:
if (status.value === MutationStatus.LOADING) {
return [2 /*return*/];
}
error.value = null;
status.value = MutationStatus.LOADING;
_c.label = 1;
case 1:
_c.trys.push([1, 4, , 5]);
_a = context;
return [4 /*yield*/, onMutate.apply(void 0, __spread(variables))];
case 2:
_a.value = _c.sent();
if (context.value) {
data.value = context.value;
}
callbackResult = callback.apply(void 0, __spread(variables));
// @ts-ignore
if (!(callbackResult instanceof Promise)) {
throw new Error('The provided callback doesn\'t return a promise!');
}
_b = data;
return [4 /*yield*/, callbackResult];
case 3:
_b.value = _c.sent();
status.value = MutationStatus.SUCCESS;
onSuccess(data.value, variables, context.value);
return [3 /*break*/, 5];
case 4:
e_1 = _c.sent();
error.value = e_1;
status.value = MutationStatus.ERROR;
onError(e_1, variables, context.value);
return [3 /*break*/, 5];
case 5: return [2 /*return*/, mutationResultReturn()];
}
});
});
};
return __assign({ mutate: mutate, status: vueDemi.computed(function () { return status.value; }) }, mutationResultReturn());
}
function usePaginateQuery(key, callback, options) {
var _this = this;
if (callback === void 0) { callback = null; }
if (options === void 0) { options = {}; }
var currentPage = vueDemi.ref(1);
var queryCachedData = vueDemi.ref(options.defaultData || null);
var requestHasNextPage = vueDemi.ref({
1: false,
});
var triggerQuery = function () { return query.fetchFromCacheOrRefetch(__spread([currentPage.value], variables)); };
var fetchPrevPage = function () { return __awaiter(_this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
if (query.isFetching.value || currentPage.value <= 1) {
return [2 /*return*/];
}
currentPage.value = currentPage.value - 1;
return [4 /*yield*/, triggerQuery()];
case 1:
_a.sent();
return [2 /*return*/];
}
});
}); };
var fetchNextPage = function () { return __awaiter(_this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
if (query.isFetching.value || !requestHasNextPage.value[currentPage.value]) {
return [2 /*return*/];
}
currentPage.value = currentPage.value + 1;
return [4 /*yield*/, triggerQuery()];
case 1:
_a.sent();
return [2 /*return*/];
}
});
}); };
var reset = function () { return __awaiter(_this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
currentPage.value = 1;
return [4 /*yield*/, triggerQuery()];
case 1:
_a.sent();
return [2 /*return*/];
}
});
}); };
key = Array.isArray(key) ? __spread(key.slice(0, 1), [{ page: currentPage }], key.slice(1)) : [key, { page: currentPage }];
var variables = useQueryKeyWatcher({
key: key,
callback: reset,
keysNotToWatch: ['page'],
}).variables;
var query = useQuery(key, callback, __assign(__assign({}, options), { manual: true, keepPreviousData: true }));
var hasMorePages = vueDemi.computed(function () { return requestHasNextPage.value[currentPage.value]; });
var init = function (_a) {
var _b;
var _c = _a === void 0 ? {} : _a, _d = _c.data, data = _d === void 0 ? null : _d, _e = _c.hasNextPage, hasNextPage = _e === void 0 ? true : _e;
if (data) {
queryCachedData.value = exports.queryDataClone(data);
}
requestHasNextPage.value = __assign(__assign({}, requestHasNextPage.value), (_b = {}, _b[currentPage.value] = query.isSuccess.value && hasNextPage, _b));
};
void triggerQuery();
// there is some kind of a bug when we us the immediate watcher with the query.data
// so we initialize the data ourselfs
init(query.data.value || {});
vueDemi.watch(query.data, init);
return __assign(__assign({}, query), { fetchPrevPage: fetchPrevPage,
fetchNextPage: fetchNextPage,
hasMorePages: hasMorePages, data: vueDemi.computed(function () { return queryCachedData.value; }), currentPage: vueDemi.computed(function () { return currentPage.value; }), isNextButtonActive: vueDemi.computed(function () { return hasMorePages.value; }), isPrevButtonActive: vueDemi.computed(function () { return currentPage.value > 1; }), isSuccess: vueDemi.computed(function () { return query.isSuccess || queryCachedData.value; }),
// show pagination buttons if the page 1 has more pages
canShowPaginationButtons: vueDemi.computed(function () { return requestHasNextPage.value[1]; }) });
}
exports.changeQueryDataCloneMethod = changeQueryDataCloneMethod;
exports.useMutation = useMutation;
exports.usePaginateQuery = usePaginateQuery;
exports.useQuery = useQuery;
exports.useQueryClient = useQueryClient;
Object.defineProperty(exports, '__esModule', { value: true });
})));