analytica-frontend-lib
Version:
Repositório público dos componentes utilizados nas plataformas da Analytica Ensino
119 lines (117 loc) • 3.29 kB
JavaScript
import {
useAuthStore
} from "./chunk-TNOKCEMB.mjs";
// src/store/userStore.ts
import { create } from "zustand";
import { createJSONStorage, persist } from "zustand/middleware";
var DEFAULT_CACHE_TTL = 5 * 60 * 1e3;
var isCacheValid = (lastFetched, cacheTTL) => {
if (!lastFetched) return false;
return Date.now() - lastFetched < cacheTTL;
};
function createUserStore(config) {
const {
apiClient,
storageKey = "user-data-storage",
cacheTTL = DEFAULT_CACHE_TTL
} = config;
const getMyData = async () => {
const response = await apiClient.get("/auth/me");
return response.data;
};
const getCurrentUserId = () => {
return useAuthStore.getState().user?.id ?? null;
};
const isCacheForCurrentUser = (cachedUserId) => {
const currentUserId = getCurrentUserId();
if (!currentUserId) {
return false;
}
if (!cachedUserId) {
return false;
}
return cachedUserId === currentUserId;
};
return create()(
persist(
(set, get) => ({
// Initial state
data: null,
cachedUserId: null,
lastFetched: null,
isLoading: false,
error: null,
/**
* Fetch user data from API with caching
*/
fetchUserData: async (force = false) => {
const { data, cachedUserId, lastFetched, isLoading } = get();
if (isLoading) return;
const cacheValidForUser = isCacheForCurrentUser(cachedUserId);
if (!force && data && cacheValidForUser && isCacheValid(lastFetched, cacheTTL)) {
return;
}
if (!cacheValidForUser && data) {
set({ data: null, cachedUserId: null, lastFetched: null });
}
try {
set({ isLoading: true, error: null });
const userData = await getMyData();
set({
data: userData,
cachedUserId: userData.user?.id ?? null,
lastFetched: Date.now(),
isLoading: false,
error: null
});
} catch (error) {
const errorMessage = error instanceof Error ? error.message : "Failed to fetch user data";
set({
isLoading: false,
error: errorMessage
});
throw error;
}
},
/**
* Clear all user data from store
*/
clearUserData: () => {
set({
data: null,
cachedUserId: null,
lastFetched: null,
isLoading: false,
error: null
});
},
/**
* Set loading state
*/
setLoading: (loading) => {
set({ isLoading: loading });
},
/**
* Set error state
*/
setError: (error) => {
set({ error });
}
}),
{
name: storageKey,
storage: createJSONStorage(() => localStorage),
// Persist data, cachedUserId and lastFetched (not loading/error states)
partialize: (state) => ({
data: state.data,
cachedUserId: state.cachedUserId,
lastFetched: state.lastFetched
})
}
)
);
}
export {
createUserStore
};
//# sourceMappingURL=chunk-R5KLBD6E.mjs.map