refactor: getEmailAlert API

This commit is contained in:
Ravinou 2025-02-16 20:44:41 +01:00
commit 7625e5af02
No known key found for this signature in database
GPG key ID: EEEE670C40F6A4D7
9 changed files with 71 additions and 76 deletions

View file

@ -9,7 +9,7 @@ import { AppriseModeEnum } from '~/types/domain/config.types';
//Components
import Error from '~/Components/UI/Error/Error';
import { Optional } from '~/types';
import { AppriseModeResponse } from '~/types/api/apprise.types';
import { AppriseModeResponse } from '~/types/api/notifications.types';
import { useFormStatus } from '~/hooks/useFormStatus';
type AppriseModeDataForm = {

View file

@ -8,7 +8,7 @@ import { useForm } from 'react-hook-form';
//Components
import Error from '~/Components/UI/Error/Error';
import { Optional } from '~/types';
import { AppriseServicesResponse } from '~/types/api/apprise.types';
import { AppriseServicesResponse } from '~/types/api/notifications.types';
import { useFormStatus } from '~/hooks/useFormStatus';
type AppriseURLsDataForm = {

View file

@ -1,22 +1,18 @@
//Lib
import { useEffect } from 'react';
import { toast, ToastOptions } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
import classes from '../UserSettings.module.css';
import { useState } from 'react';
import { SpinnerCircularFixed } from 'spinners-react';
import { IconExternalLink } from '@tabler/icons-react';
import Link from 'next/link';
import { useEffect, useState } from 'react';
import { toast, ToastOptions } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
import { SpinnerCircularFixed } from 'spinners-react';
import classes from '../UserSettings.module.css';
//Components
import Error from '~/Components/UI/Error/Error';
import Switch from '~/Components/UI/Switch/Switch';
import { useFormStatus } from '~/hooks/useFormStatus';
import { Optional } from '~/types';
type EmailAlertDataForm = {
emailAlert: boolean;
};
import { EmailAlert } from '~/types/api/notifications.types';
export default function EmailAlertSettings() {
//Var
@ -32,8 +28,7 @@ export default function EmailAlertSettings() {
onClose: () => setIsSwitchDisabled(false),
};
const { isLoading, isSaved, error, setIsLoading, handleSuccess, handleError, clearError } =
useFormStatus();
const { error, handleError, clearError } = useFormStatus();
////State
const [isSendingTestNotification, setIsSendingTestNotification] = useState(false);
@ -53,7 +48,7 @@ export default function EmailAlertSettings() {
},
});
const data: Optional<EmailAlertDataForm> = await response.json();
const data: Optional<EmailAlert> = await response.json();
setIsAlertEnabled(data?.emailAlert ?? false);
setIsSwitchDisabled(false);
} catch (error) {
@ -67,7 +62,7 @@ export default function EmailAlertSettings() {
////Functions
//Switch to enable/disable Email notifications
const onChangeSwitchHandler = async (data: EmailAlertDataForm) => {
const onChangeSwitchHandler = async (data: EmailAlert) => {
clearError();
setIsSwitchDisabled(true);
await fetch('/api/account/updateEmailAlert', {
@ -88,7 +83,7 @@ export default function EmailAlertSettings() {
handleError('Update email alert setting failed.');
}
})
.catch((error) => {
.catch(() => {
handleError('Update email alert setting failed.');
})
.finally(() => {

View file

@ -5,7 +5,7 @@ import { authOptions } from '../auth/[...nextauth]';
import { getServerSession } from 'next-auth/next';
import { NextApiRequest, NextApiResponse } from 'next';
import { BorgWarehouseUser } from '~/types/domain/config.types';
import { AppriseAlertResponse } from '~/types/api/apprise.types';
import { AppriseAlertResponse } from '~/types/api/notifications.types';
import { ErrorResponse } from '~/types/api/error.types';
export default async function handler(

View file

@ -4,7 +4,7 @@ import path from 'path';
import { authOptions } from '../auth/[...nextauth]';
import { getServerSession } from 'next-auth/next';
import { NextApiRequest, NextApiResponse } from 'next';
import { AppriseModeResponse } from '~/types/api/apprise.types';
import { AppriseModeResponse } from '~/types/api/notifications.types';
import { ErrorResponse } from '~/types/api/error.types';
import { BorgWarehouseUser } from '~/types/domain/config.types';

View file

@ -4,7 +4,7 @@ import path from 'path';
import { authOptions } from '../auth/[...nextauth]';
import { getServerSession } from 'next-auth/next';
import { NextApiRequest, NextApiResponse } from 'next';
import { AppriseServicesResponse } from '~/types/api/apprise.types';
import { AppriseServicesResponse } from '~/types/api/notifications.types';
import { ErrorResponse } from '~/types/api/error.types';
import { BorgWarehouseUser } from '~/types/domain/config.types';

View file

@ -1,57 +0,0 @@
//Lib
import { promises as fs } from 'fs';
import path from 'path';
import { authOptions } from '../auth/[...nextauth]';
import { getServerSession } from 'next-auth/next';
export default async function handler(req, res) {
if (req.method == 'GET') {
//Verify that the user is logged in.
const session = await getServerSession(req, res, authOptions);
if (!session) {
res.status(401).json({ message: 'You must be logged in.' });
return;
}
try {
//Read the users file
//Find the absolute path of the json directory
const jsonDirectory = path.join(process.cwd(), '/config');
let usersList = await fs.readFile(jsonDirectory + '/users.json', 'utf8');
//Parse the usersList
usersList = JSON.parse(usersList);
//Verify that the user of the session exists
const userIndex = usersList.map((user) => user.username).indexOf(session.user.name);
if (userIndex === -1) {
res.status(400).json({
message: 'User is incorrect. Please, logout to update your session.',
});
return;
} else {
//Send the emailAlert bool
res.status(200).json({
emailAlert: usersList[userIndex].emailAlert,
});
return;
}
} catch (error) {
//Log for backend
console.log(error);
//Log for frontend
if (error.code == 'ENOENT') {
res.status(500).json({
status: 500,
message: 'No such file or directory',
});
} else {
res.status(500).json({
status: 500,
message: 'API error, contact the administrator',
});
}
return;
}
} else {
res.status(405).json({ message: 'Bad request on API' });
}
}

View file

@ -0,0 +1,53 @@
//Lib
import { promises as fs } from 'fs';
import path from 'path';
import { authOptions } from '../auth/[...nextauth]';
import { getServerSession } from 'next-auth/next';
import { NextApiRequest, NextApiResponse } from 'next';
import { EmailAlert } from '~/types/api/notifications.types';
import { ErrorResponse } from '~/types/api/error.types';
import { BorgWarehouseUser } from '~/types/domain/config.types';
export default async function handler(
req: NextApiRequest,
res: NextApiResponse<EmailAlert | ErrorResponse>
) {
if (req.method !== 'GET') {
res.status(405).json({ message: 'Bad request on API' });
return;
}
//Verify that the user is logged in.
const session = await getServerSession(req, res, authOptions);
if (!session) {
res.status(401).json({ message: 'You must be logged in.' });
return;
}
try {
//Read the users file
const jsonDirectory = path.join(process.cwd(), '/config');
const fileContent = await fs.readFile(jsonDirectory + '/users.json', 'utf8');
//Parse the usersList
const usersList: Array<BorgWarehouseUser> = JSON.parse(fileContent);
//Verify that the user of the session exists
const user = usersList.find((u) => u.username === session.user?.name);
if (!user) {
res.status(400).json({
message: 'User is incorrect. Please, logout to update your session.',
});
return;
}
res.status(200).json({ emailAlert: user.emailAlert });
} catch (error: any) {
console.log(error);
const errorMessage =
error.code === 'ENOENT'
? 'No such file or directory'
: 'API error, contact the administrator';
res.status(500).json({ status: 500, message: errorMessage });
}
}

View file

@ -12,3 +12,7 @@ export type AppriseServicesResponse = {
export type AppriseAlertResponse = {
appriseAlert?: boolean;
};
export type EmailAlert = {
emailAlert?: boolean;
};