From 6e429f4f27aa70b455c0c9d4b19b08b5b04acbf5 Mon Sep 17 00:00:00 2001 From: Mathis Date: Thu, 25 Apr 2024 16:56:50 +0200 Subject: [PATCH] feat(services): add new BrandService with createBrand function This commit introduces the new file `brand.service.ts` under services. Specifically, it implements the `createBrand` method which handles the creation of a new brand instance in the database if there's no existing brand with the same slug name. The function returns a promise containing the operation result. A UUID is also generated as `brandId`, and several logs will be recorded in different situations. Issue: #13 Signed-off-by: Mathis --- src/services/brand.service.ts | 41 +++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 src/services/brand.service.ts diff --git a/src/services/brand.service.ts b/src/services/brand.service.ts new file mode 100644 index 0000000..ff3bd7b --- /dev/null +++ b/src/services/brand.service.ts @@ -0,0 +1,41 @@ +import 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} A promise that resolves to the result of the operation. + */ +async function createBrand(data: IDbBrand): Promise { + 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' }; +} + +const BrandService = { + create: createBrand +} + +export default BrandService; \ No newline at end of file