feat(services): update user service dynamic types and enhance error handling

- Refactored `editUserService` function to use `IUserUpdate` type for `inputData` instead of `IDbUser`.
- Enhanced error handling in `editUserService` and `deleteUserService` by checking for affected rows in the returned result.
- Updated `deleteUserService` from using MongoDB method to MySqlService method.

Issue: #18
Signed-off-by: Mathis <yidhra@tuta.io>
This commit is contained in:
Mathis H (Avnyr) 2024-05-02 15:37:39 +02:00
parent 1cbc771251
commit bdfc598218
Signed by: Mathis
GPG Key ID: DD9E0666A747D126

View File

@ -8,6 +8,7 @@ import MySqlService from "@services/mysql.service";
import { isDebugMode } from "@utils/debugState";
import { Logger } from "tslog";
import { v4 } from "uuid";
import {IUserUpdate} from "@interfaces/services/IUserUpdate";
const logger = new Logger({
name: "UserService",
@ -294,8 +295,8 @@ async function getAllUsersService(): Promise<Array<IDbUser> | ISError> {
}
async function editUserService(
targetId,
inputData: IDbUser,
targetId: string,
inputData: IUserUpdate,
): Promise<ISError | boolean> {
if (!targetId || targetId.length !== 36) {
logger.info(`\n\n> Invalid ID (${targetId})\n`);
@ -305,18 +306,20 @@ async function editUserService(
};
}
const dbUser = await MySqlService.User.getById(DbHandler, targetId);
if (!dbUser.id) {
if (!dbUser[0] || !dbUser[0].id) {
return {
error: ErrorType.NotFound,
message: "User not found.",
};
}
const result = await MySqlService.User.update(DbHandler, {
username: inputData.username,
firstname: inputData.firstname,
lastname: inputData.lastname,
dob: inputData.dob,
});
const result = await MySqlService.User.update(DbHandler, inputData);
if (result.affectedRows === 0) {
return {
error: ErrorType.DatabaseError,
message: "An unknown error occurred.",
};
}
return true;
}
/**
@ -325,13 +328,12 @@ async function editUserService(
* @param {string} targetId - The ID of the user to be deleted.
* @return {Promise<boolean>} - A promise that resolves to true if the user is successfully deleted, or false if an error occurs.
*/
async function deleteUserService(targetId) {
async function deleteUserService(targetId: string): Promise<boolean> {
logger.info(`Deleting user ${targetId}`);
try {
await Db.collection("users").deleteOne({
id: targetId,
});
return true;
const DeleteResult = await MySqlService.User.delete(DbHandler, targetId)
if (DeleteResult.affectedRows !== 0) return true;
return false;
} catch (e) {
logger.warn(e);
return false;