amplifyquery
Version:
206 lines (205 loc) • 7.58 kB
JavaScript
var __awaiter = (this && this.__awaiter) || function (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());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.queryClient = void 0;
exports.getQueryClient = getQueryClient;
exports.configure = configure;
exports.createQueryKeys = createQueryKeys;
exports.invalidateModel = invalidateModel;
exports.invalidateModelItem = invalidateModelItem;
exports.invalidateModelByField = invalidateModelByField;
exports.invalidateAll = invalidateAll;
exports.ensureMutationsFlushed = ensureMutationsFlushed;
const react_native_mmkv_1 = require("react-native-mmkv");
const react_query_1 = require("@tanstack/react-query");
const react_query_persist_client_1 = require("@tanstack/react-query-persist-client");
// Default configuration
const config = {
isCachingEnabled: process.env.EXPO_PUBLIC_DISABLE_STORAGE_CACHE !== "true",
queryClientConfig: {
defaultOptions: {
queries: {
// Default cache settings - increased from defaults
staleTime: 5 * 60 * 1000, // Data remains "fresh" for 5 minutes
gcTime: 30 * 60 * 1000, // Inactive query cache kept for 30 minutes (formerly cacheTime)
retry: 1, // Retry only once on failure
refetchOnWindowFocus: false, // Disable refetch on window focus (important for mobile)
refetchOnReconnect: true, // Refetch on network reconnect
},
mutations: {
retry: 1, // Retry only once on failure
onError: (error) => {
console.error("Mutation error:", error);
},
},
},
},
storage: {
mmkvId: "mmkv.amplify-query.cache",
cacheKey: "REACT_QUERY_OFFLINE_CACHE",
maxAge: 1000 * 60 * 60 * 24 * 7, // 7 days
},
};
// MMKV instance
let storageInstance; // Renamed from 'storage' to avoid conflict with ConfigOptions.storage
// Function to create MMKV persister
function createMmkvPersister() {
var _a, _b;
// Initialize or reuse MMKV instance
if (!storageInstance) {
storageInstance = new react_native_mmkv_1.MMKV({
id: ((_a = config.storage) === null || _a === void 0 ? void 0 : _a.mmkvId) || "mmkv.amplify-query.cache",
});
}
// Check cache key
const cacheKey = ((_b = config.storage) === null || _b === void 0 ? void 0 : _b.cacheKey) || "REACT_QUERY_OFFLINE_CACHE";
return {
persistClient: (client) => {
try {
// Convert object to JSON string
const clientStr = JSON.stringify(client);
storageInstance.set(cacheKey, clientStr);
}
catch (error) {
console.error("Error saving cache:", error);
}
},
restoreClient: () => {
try {
const clientStr = storageInstance.getString(cacheKey);
if (!clientStr)
return null;
// Convert string back to object
return JSON.parse(clientStr);
}
catch (error) {
console.error("Error restoring cache:", error);
return null;
}
},
removeClient: () => {
try {
storageInstance.delete(cacheKey);
}
catch (error) {
console.error("Error removing cache:", error);
}
},
};
}
/**
* TanStack Query client
*/
exports.queryClient = new react_query_1.QueryClient(config.queryClientConfig);
/**
* Get the current query client instance
* @returns The QueryClient instance
*/
function getQueryClient() {
return exports.queryClient;
}
/**
* AmplifyQuery configuration
* @param options Configuration options
*/
function configure(options = {}) {
var _a;
// Backup previous config
const prevConfig = Object.assign({}, config);
// Apply new config
Object.assign(config, options);
// Recreate client if QueryClient config changed
if (options.queryClientConfig &&
JSON.stringify(options.queryClientConfig) !==
JSON.stringify(prevConfig.queryClientConfig)) {
exports.queryClient = new react_query_1.QueryClient(config.queryClientConfig);
}
// Apply caching config
if (config.isCachingEnabled) {
console.log("🏃♀️ React Query offline cache is enabled with MMKV.");
// Create new persister if config changed
const mmkvPersister = createMmkvPersister();
(0, react_query_persist_client_1.persistQueryClient)({
queryClient: exports.queryClient,
persister: mmkvPersister,
// Additional options
maxAge: ((_a = config.storage) === null || _a === void 0 ? void 0 : _a.maxAge) || 1000 * 60 * 60 * 24 * 7, // Default 7 days
dehydrateOptions: {
shouldDehydrateQuery: (query) => {
// Filter for queries not to cache (implement if needed)
return true;
},
},
});
}
else {
console.log("🏃♀️ React Query offline cache is disabled via flag.");
}
}
/**
* Create query keys from model names
* @param modelNames Array of model names
* @returns Object of query keys per model
*/
function createQueryKeys(modelNames) {
const queryKeys = {};
modelNames.forEach((modelName) => {
queryKeys[modelName] = [modelName];
});
return queryKeys;
}
/**
* Invalidate all queries for a model
* @param modelName Model name
*/
function invalidateModel(modelName) {
exports.queryClient.invalidateQueries({ queryKey: [modelName] });
}
/**
* Invalidate a model item with a specific ID
* @param modelName Model name
* @param id Item ID
*/
function invalidateModelItem(modelName, id) {
exports.queryClient.invalidateQueries({ queryKey: [modelName, id] });
}
/**
* Invalidate model items with a specific field value
* @param modelName Model name
* @param field Field name
* @param value Field value
*/
function invalidateModelByField(modelName, field, value) {
exports.queryClient.invalidateQueries({ queryKey: [modelName, "by", field, value] });
}
/**
* Invalidate all query caches (full app reset)
*/
function invalidateAll() {
exports.queryClient.invalidateQueries();
}
/**
* Ensure important changes are synced to server before app closes
*/
function ensureMutationsFlushed() {
return __awaiter(this, void 0, void 0, function* () {
return exports.queryClient.isMutating()
? new Promise((resolve) => {
const unsubscribe = exports.queryClient.getMutationCache().subscribe(() => {
if (!exports.queryClient.isMutating()) {
unsubscribe();
resolve(true);
}
});
})
: Promise.resolve(true);
});
}
;