datasquirel/package-shared/functions/api/users/api-update-user.ts

100 lines
2.6 KiB
TypeScript
Raw Normal View History

2024-12-06 10:31:24 +00:00
// @ts-check
2025-01-10 19:10:28 +00:00
import updateDbEntry from "../../backend/db/updateDbEntry";
import encrypt from "../../dsql/encrypt";
import hashPassword from "../../dsql/hashPassword";
import varDatabaseDbHandler from "../../backend/varDatabaseDbHandler";
type Param = {
payload: { [s: string]: any };
dbFullName: string;
updatedUserId: string | number;
useLocal?: boolean;
dbSchema?: import("../../../types").DSQL_DatabaseSchemaType;
};
type Return = { success: boolean; payload?: any; msg?: string };
2024-12-06 10:31:24 +00:00
/**
* # Update API User Function
*/
2025-01-10 19:10:28 +00:00
export default async function apiUpdateUser({
2024-12-06 11:55:03 +00:00
payload,
dbFullName,
2024-12-08 08:58:57 +00:00
updatedUserId,
2024-12-06 11:55:03 +00:00
useLocal,
2024-12-08 08:58:57 +00:00
dbSchema,
2025-01-10 19:10:28 +00:00
}: Param): Promise<Return> {
2024-12-08 08:58:57 +00:00
const existingUserQuery = `SELECT * FROM users WHERE id = ?`;
const existingUserValues = [updatedUserId];
const existingUser = await varDatabaseDbHandler({
queryString: existingUserQuery,
queryValuesArray: existingUserValues,
database: dbFullName,
useLocal,
});
if (!existingUser?.[0]) {
return {
success: false,
msg: "User not found",
};
}
2024-12-06 10:31:24 +00:00
const data = (() => {
const reqBodyKeys = Object.keys(payload);
2024-12-08 08:58:57 +00:00
const targetTableSchema = (() => {
try {
const targetDatabaseSchema = dbSchema?.tables?.find(
(tbl) => tbl.tableName == "users"
);
return targetDatabaseSchema;
} catch (error) {
return undefined;
}
})();
2024-12-06 10:31:24 +00:00
/** @type {any} */
2025-01-10 19:10:28 +00:00
const finalData: any = {};
2024-12-06 10:31:24 +00:00
reqBodyKeys.forEach((key) => {
2024-12-08 08:58:57 +00:00
const targetFieldSchema = targetTableSchema?.fields?.find(
(field) => field.fieldName == key
);
if (key?.match(/^date_|^id$|^uuid$/)) return;
let value = payload[key];
if (targetFieldSchema?.encrypted) {
value = encrypt({ data: value });
}
finalData[key] = value;
2024-12-06 10:31:24 +00:00
});
2024-12-08 08:58:57 +00:00
if (finalData.password && typeof finalData.password == "string") {
finalData.password = hashPassword({ password: finalData.password });
}
2024-12-06 10:31:24 +00:00
return finalData;
})();
const updateUser = await updateDbEntry({
dbContext: "Dsql User",
paradigm: "Full Access",
dbFullName,
tableName: "users",
identifierColumnName: "id",
2024-12-08 08:58:57 +00:00
identifierValue: updatedUserId,
2024-12-06 10:31:24 +00:00
data: data,
2024-12-06 11:55:03 +00:00
useLocal,
2024-12-06 10:31:24 +00:00
});
return {
success: true,
payload: updateUser,
};
2025-01-10 19:10:28 +00:00
}