CoreControl/hooks/useNotifications.ts

85 lines
2.7 KiB
TypeScript
Raw Normal View History

2025-05-24 23:03:10 +02:00
import { useState, useEffect, useCallback } from "react";
import axios from "axios";
2025-05-25 21:43:42 +02:00
interface NotificationTest {
id: number;
notificationProviderId: number;
sent: boolean;
success: boolean;
}
2025-05-24 23:03:10 +02:00
const useNotifications = () => {
const [notifications, setNotifications] = useState([]);
const [loading, setLoading] = useState(false);
2025-05-25 21:43:42 +02:00
const [notificationTest, setNotificationTest] = useState<NotificationTest | null>(null);
2025-05-24 23:03:10 +02:00
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;
2025-05-25 00:32:16 +02:00
})
.catch(err => {
throw err.response?.data?.error || 'An error occurred';
2025-05-24 23:03:10 +02:00
});
};
2025-05-25 00:56:54 +02:00
const deleteNotification = (notificationId: number): Promise<string> | string => {
return axios.delete('/api/notifications/delete', { params: { notificationId } })
2025-05-24 23:03:10 +02:00
.then(() => {
return "Notification deleted successfully";
})
.catch(err => {
throw err.response?.data?.error || 'An error occurred';
});
}
2025-05-25 21:03:37 +02:00
const testNotification = (notificationProviderId: number): Promise<string> | string => {
return axios.post('/api/notifications/test', { notificationProviderId })
.then((response) => {
return response.data.notificationTest;
})
.catch(err => {
throw err.response?.data?.error || 'An error occurred';
});
}
2025-05-25 21:43:42 +02:00
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';
});
}
2025-05-25 00:32:16 +02:00
return {
notifications,
loading,
addNotification,
deleteNotification,
2025-05-25 21:03:37 +02:00
loadNotifications,
2025-05-25 21:43:42 +02:00
testNotification,
getNotificationTest,
notificationTest
2025-05-25 00:32:16 +02:00
};
}
export default useNotifications;