CoreControl/hooks/useNotifications.ts
2025-05-25 22:01:15 +02:00

89 lines
2.8 KiB
TypeScript

import { useState, useEffect, useCallback } from "react";
import axios from "axios";
interface NotificationTest {
id: number;
notificationProviderId: number;
sent: boolean;
success: boolean;
}
const useNotifications = () => {
const [notifications, setNotifications] = useState([]);
const [loading, setLoading] = useState(false);
const [notificationTest, setNotificationTest] = useState<NotificationTest | null>(null);
const loadNotifications = useCallback(() => {
setLoading(true);
axios.get('/api/notifications/get').then((response) => {
setNotifications(response.data.notifications);
setLoading(false);
});
}, []);
useEffect(() => {
loadNotifications();
}, [loadNotifications]);
const addNotification = (name: string, type: string, config: string): Promise<string> | string => {
if(name.length < 3) {
return 'Notification name must be at least 3 characters long';
}
return axios.post('/api/notifications/add', { name, type, config })
.then((response) => {
return response.data.notification;
})
.catch(err => {
throw err.response?.data?.error || 'An error occurred';
});
};
const deleteNotification = (notificationId: number): Promise<string> | string => {
return axios.delete('/api/notifications/delete', { params: { notificationId } })
.then(() => {
return "Notification deleted successfully";
})
.catch(err => {
throw err.response?.data?.error || 'An error occurred';
});
}
const testNotification = (notificationProviderId: number): Promise<number> | number => {
return axios.post('/api/notifications/test', { notificationProviderId })
.then((response) => {
if(response.data.notificationTest) {
return Number(response.data.notificationTest.id);
} else {
throw new Error('Notification test not found');
}
})
.catch(err => {
throw err.response?.data?.error || 'An error occurred';
});
}
const getNotificationTest = (notificationTestId: number): Promise<string> | string => {
return axios.get('/api/notifications/test/get', { params: { notificationTestId } })
.then((response) => {
setNotificationTest(response.data.notificationTest);
return response.data.notificationTest;
})
.catch(err => {
throw err.response?.data?.error || 'An error occurred';
});
}
return {
notifications,
loading,
addNotification,
deleteNotification,
loadNotifications,
testNotification,
getNotificationTest,
notificationTest
};
}
export default useNotifications;