datasquirel/package-shared/functions/backend/parseDbResults.ts
2025-01-10 20:10:28 +01:00

78 lines
2.2 KiB
TypeScript

// @ts-check
import decrypt from "../dsql/decrypt";
import defaultFieldsRegexp from "./defaultFieldsRegexp";
type Param = {
unparsedResults: any[];
tableSchema?: import("../../types").DSQL_TableSchemaType;
};
/**
* Parse Database results
* ==============================================================================
* @description this function takes a database results array gotten from a DB handler
* function, decrypts encrypted fields, and returns an updated array with no encrypted
* fields
*/
export default async function parseDbResults({
unparsedResults,
tableSchema,
}: Param): Promise<any[] | null> {
/**
* Declare variables
*
* @description Declare "results" variable
*/
let parsedResults = [];
try {
/**
* Declare variables
*
* @description Declare "results" variable
*/
for (let pr = 0; pr < unparsedResults.length; pr++) {
let result = unparsedResults[pr];
let resultFieldNames = Object.keys(result);
for (let i = 0; i < resultFieldNames.length; i++) {
const resultFieldName = resultFieldNames[i];
let resultFieldSchema = tableSchema?.fields[i];
if (resultFieldName?.match(defaultFieldsRegexp)) {
continue;
}
let value = result[resultFieldName];
if (typeof value !== "number" && !value) {
// parsedResults.push(result);
continue;
}
if (resultFieldSchema?.encrypted) {
if (value?.match(/./)) {
result[resultFieldName] = decrypt({
encryptedString: value,
});
}
}
}
parsedResults.push(result);
}
/**
* Declare variables
*
* @description Declare "results" variable
*/
return parsedResults;
} catch (/** @type {any} */ error: any) {
console.log("ERROR in parseDbResults Function =>", error.message);
return unparsedResults;
}
}