brief-05-back/src/services/brand.service.ts
Mathis 90cd80e540
feat(services): add updateBrand function to BrandService
A new function `updateBrand` has been introduced to `BrandService`. This function handles updating a brand in the database, including checks for missing `id`, brand existence by `slug_name`, and logging for successful or failed updates.

Issue: #13
Signed-off-by: Mathis <yidhra@tuta.io>
2024-04-26 09:30:03 +02:00

72 lines
2.2 KiB
TypeScript

import type IDbBrand from "@interfaces/database/IDbBrand";
import MysqlService from "@services/mysql.service";
import {Logger} from "tslog";
import { v4 as uuidv4 } from 'uuid';
const DbHandler = new MysqlService.Handler('BrandService')
const logger = new Logger({name: 'BrandService'})
//SEC Blob validation
/**
* Creates a brand in the database with the given data.
*
* @param {IDbBrand} data - The data of the brand to be created.
* @return {Promise<unknown>} A promise that resolves to the result of the operation.
*/
async function createBrand(data: IDbBrand): Promise<unknown> {
const doesExist = await MysqlService.Brand.getBySlug(DbHandler, data.slug_name);
if (doesExist) {
logger.error(`Brand already exists (${data.slug_name})`)
return {error: 'exist'}
}
const brandId = uuidv4();
const createdBrand = await MysqlService.Brand.insert(DbHandler, {
id: brandId,
slug_name: `${data.slug_name}`,
display_name: `${data.display_name}`,
image_blob: data.image_blob
});
if (createdBrand) {
logger.info(`Brand created successfully (${data.slug_name})`);
return { success: true, brand: createdBrand };
}
logger.error(`Failed to create brand (${data.slug_name})`);
return { error: 'failed' };
}
/**
* Updates a brand in the database.
*
* @param {IDbBrand} data - The brand data to update.
* @returns {Promise<boolean>} - Indicates whether the update was successful or not.
*/
async function updateBrand(data: IDbBrand): Promise<boolean> {
if (!data.id) {
logger.error("Brand ID is missing");
return false;
}
const doesExist = await MysqlService.Brand.getBySlug(DbHandler, data.slug_name);
if (doesExist && doesExist.id !== data.id) {
logger.error(`Brand already exists (${data.slug_name})`);
return false;
}
const updatedBrand = await MysqlService.Brand.update(DbHandler, {
id: data.id,
slug_name: `${data.slug_name}`,
display_name: `${data.display_name}`,
image_blob: data.image_blob
});
if (updatedBrand) {
logger.info(`Brand updated successfully (${data.slug_name})`);
return true;
}
logger.error(`Failed to update brand (${data.slug_name})`);
return false;
}
const BrandService = {
create: createBrand,
update: updateBrand
}
export default BrandService;