feat(services): add factorize method and refactor update method in mysql.service

- The `factorize` method was added to `mysql.service.ts` to convert input data into a database query.
- The `update` method was refactored; unnecessary data fields were removed and a check for the `gdpr` field was added. A corresponding interface, `IUserUpdate`, was also imported at the beginning of the file.

Issue: #18
Signed-off-by: Mathis <yidhra@tuta.io>
This commit is contained in:
Mathis H (Avnyr) 2024-04-30 16:15:19 +02:00
parent 3d5ea6ac30
commit df28d3aa52
Signed by: Mathis
GPG Key ID: DD9E0666A747D126

View File

@ -7,6 +7,8 @@ import type { IDbUser } from "@interfaces/database/IDbUser";
import type { IDbVehicle } from "@interfaces/database/IDbVehicle"; import type { IDbVehicle } from "@interfaces/database/IDbVehicle";
import mysql, { type Connection, type ConnectionOptions } from "mysql2"; import mysql, { type Connection, type ConnectionOptions } from "mysql2";
import { Logger } from "tslog"; import { Logger } from "tslog";
import {IUserUpdate} from "@interfaces/services/IUserUpdate";
import {IDbFactorizeInput, IDbFactorizeOutput} from "@interfaces/database/IDbFactorize";
const access: ConnectionOptions = { const access: ConnectionOptions = {
host: `${process.env["MYSQL_HOST"]}`, host: `${process.env["MYSQL_HOST"]}`,
@ -52,6 +54,40 @@ class MysqlHandler {
}); });
} }
/**
* Factorize the input data values into a database query.
*
* @param {IDbFactorizeInput} data - The input data containing values to factorize.
* @return {Promise<IDbFactorizeOutput>} - A promise resolving to the factorized output.
*/
factorize(data: IDbFactorizeInput): Promise<IDbFactorizeOutput> {
return new Promise((resolve, reject)=>{
try {
const _sqlQueryKeys = Object.keys(data.values).map((key: string) => `\'${key}\' = ?`)
const values = Object.values(data.values).map((val)=>val)
this.Logger.debug(`\n\n>-> Factorized ${_sqlQueryKeys.length} keys for a prepare Query.\n>-> Action: ${data.actionName}\n`)
const sqlQueryKeys = _sqlQueryKeys.join(', ')
const factorizedOutput: IDbFactorizeOutput = {
_keysTemplate: sqlQueryKeys,
totalFields: _sqlQueryKeys.length,
_valuesArray: values
}
resolve(factorizedOutput);
} catch (err) {
if (data.throwOnError) throw new Error(`${err}`)
this.Logger.error(`\n|\n${err}\n|`)
reject(`${err}`)
}
})
}
/**
* Executes a query using the provided queryString and values.
* @param {string} queryString - The SQL query string to execute.
* @param {Array<string | boolean | Date | number>} values - The values to be inserted into the query.
* @returns {Promise<unknown>} - A promise that resolves with the query results or rejects with an error.
*/
execute( execute(
queryString: string, queryString: string,
values: Array<string | boolean | Date | number>, values: Array<string | boolean | Date | number>,
@ -138,38 +174,25 @@ const MySqlService = {
/** /**
* Updates a user in the database. * Updates a user in the database.
* @param {MysqlHandler} handler - The MySQL handler object. * @param {MysqlHandler} handler - The MySQL handler object.
* @param {IDbUser} data - The updated user data. * @param {IUserUpdate} data - The updated user data.
* @returns {Promise<IDbStatusResult>} - A promise that resolves to the result of the update operation. * @returns {Promise<IDbStatusResult>} - A promise that resolves to the result of the update operation.
* @throws {Error} If an error occurs during the update operation. * @throws {Error} If an error occurs during the update operation.
*/ */
update(handler: MysqlHandler, data: IDbUser): Promise<IDbStatusResult> { update(handler: MysqlHandler, data: IUserUpdate): Promise<IDbStatusResult> {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
if (!data.id) return reject("Id is undefined"); if (!data.id) return reject("Id is undefined");
if (data.id.length !== 36) return reject("Id invalid"); if (data.id.length !== 36) return reject("Id invalid");
if (data.gdpr && typeof data.gdpr !== typeof Date) {
return reject("Invalid gdpr date.")
}
try { try {
const _values = [];
const _template = ` const _template = `
${data.username ? "`username` = ?," : null} ${data.username ? "`username` = ?," && _values.push(data.username) as unknown as void : null}
${data.firstname ? "`firstname` = ?," : null} ${data.firstname ? "`firstname` = ?," : null}
${data.lastname ? "`lastname` = ?," : null} ${data.lastname ? "`lastname` = ?," : null}
${data.dob ? "`dob` = ?," : null} ${data.dob ? "`dob` = ?," : null}
${data.email ? "`email` = ?," : null} ${data.gdpr ? "`gdpr` = ?," : null}`
${data.is_mail_verified ? "`is_mail_verified` = ?," : null}
${data.is_admin ? "`is_admin` = ?," : null}
${data.gdpr ? "`gdpr` = ?," : null}
${data.hash ? "`hash` = ?" : null}`;
const _values = [
data.username,
data.firstname,
data.lastname,
data.dob,
data.email,
data.is_mail_verified,
data.is_admin,
data.gdpr,
data.hash,
data.id,
];
const _sql = `UPDATE "users" SET ${_template} WHERE 'id' = ?`; const _sql = `UPDATE "users" SET ${_template} WHERE 'id' = ?`;
handler.execute(_sql, _values).then((result) => { handler.execute(_sql, _values).then((result) => {