Files
rmser/rmser-view/src/shared/hooks/useUserRole.ts
SERTY 51bc5bf8f0 0302-отрефакторил в нормальный вид на мобилу и десктоп
сразу выкинул пути в импортах и добавил алиас для корня
2026-02-03 12:49:20 +03:00

64 lines
2.1 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { useEffect, useState, useCallback } from 'react';
import { api } from '../api';
import type { UserSettings, UserRole } from '../types';
interface UseUserRoleResult {
/** Роль текущего пользователя или null если не загружено */
role: UserRole | null;
/** Полные настройки пользователя */
settings: UserSettings | null;
/** Состояние загрузки */
loading: boolean;
/** Ошибка загрузки */
error: string | null;
/** Функция для повторной загрузки настроек */
refetch: () => Promise<void>;
/** Является ли пользователь оператором */
isOperator: boolean;
/** Является ли пользователь админом или владельцем */
isAdminOrOwner: boolean;
}
/**
* Хук для получения роли пользователя и настроек.
* Автоматически загружает настройки при монтировании компонента.
*/
export const useUserRole = (): UseUserRoleResult => {
const [settings, setSettings] = useState<UserSettings | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const fetchSettings = useCallback(async () => {
setLoading(true);
setError(null);
try {
const data = await api.getSettings();
setSettings(data);
} catch (err) {
console.error('Ошибка при загрузке настроек:', err);
setError(err instanceof Error ? err.message : 'Не удалось загрузить настройки');
} finally {
setLoading(false);
}
}, []);
// Загружаем настройки при монтировании
useEffect(() => {
fetchSettings();
}, [fetchSettings]);
const role = settings?.role ?? null;
const isOperator = role === 'OPERATOR';
const isAdminOrOwner = role === 'ADMIN' || role === 'OWNER';
return {
role,
settings,
loading,
error,
refetch: fetchSettings,
isOperator,
isAdminOrOwner,
};
};