datasquirel/dist/package-shared/functions/api/users/api-update-user.js
Benjamin Toby 7e8bb37c09 Updates
2025-07-05 14:59:30 +01:00

65 lines
2.5 KiB
JavaScript

// @ts-check
import updateDbEntry from "../../backend/db/updateDbEntry";
import encrypt from "../../dsql/encrypt";
import hashPassword from "../../dsql/hashPassword";
import varDatabaseDbHandler from "../../backend/varDatabaseDbHandler";
/**
* # Update API User Function
*/
export default async function apiUpdateUser({ payload, dbFullName, updatedUserId, dbSchema, }) {
const existingUserQuery = `SELECT * FROM ${dbFullName}.users WHERE id = ?`;
const existingUserValues = [updatedUserId];
const existingUser = await varDatabaseDbHandler({
queryString: existingUserQuery,
queryValuesArray: existingUserValues,
database: dbFullName,
});
if (!(existingUser === null || existingUser === void 0 ? void 0 : existingUser[0])) {
return {
success: false,
msg: "User not found",
};
}
const data = (() => {
const reqBodyKeys = Object.keys(payload);
const targetTableSchema = (() => {
var _a;
try {
const targetDatabaseSchema = (_a = dbSchema === null || dbSchema === void 0 ? void 0 : dbSchema.tables) === null || _a === void 0 ? void 0 : _a.find((tbl) => tbl.tableName == "users");
return targetDatabaseSchema;
}
catch (error) {
return undefined;
}
})();
/** @type {any} */
const finalData = {};
reqBodyKeys.forEach((key) => {
var _a;
const targetFieldSchema = (_a = targetTableSchema === null || targetTableSchema === void 0 ? void 0 : targetTableSchema.fields) === null || _a === void 0 ? void 0 : _a.find((field) => field.fieldName == key);
if (key === null || key === void 0 ? void 0 : key.match(/^date_|^id$|^uuid$/))
return;
let value = payload[key];
if (targetFieldSchema === null || targetFieldSchema === void 0 ? void 0 : targetFieldSchema.encrypted) {
value = encrypt({ data: value });
}
finalData[key] = value;
});
if (finalData.password && typeof finalData.password == "string") {
finalData.password = hashPassword({ password: finalData.password });
}
return finalData;
})();
const updateUser = await updateDbEntry({
dbFullName,
tableName: "users",
identifierColumnName: "id",
identifierValue: updatedUserId,
data: data,
});
return {
success: true,
payload: updateUser,
};
}