87 lines
2.4 KiB
TypeScript
87 lines
2.4 KiB
TypeScript
import updateDbEntry from "../../backend/db/updateDbEntry";
|
|
import encrypt from "../../dsql/encrypt";
|
|
import hashPassword from "../../dsql/hashPassword";
|
|
import dbHandler from "../../backend/dbHandler";
|
|
import { APIResponseObject, ApiUpdateUserParams } from "../../../types";
|
|
import grabDbFullName from "../../../utils/grab-db-full-name";
|
|
|
|
/**
|
|
* # Update API User Function
|
|
*/
|
|
export default async function apiUpdateUser({
|
|
payload,
|
|
updatedUserId,
|
|
dbSchema,
|
|
database,
|
|
dbUserId,
|
|
}: ApiUpdateUserParams): Promise<APIResponseObject> {
|
|
const dbFullName = grabDbFullName({ dbName: database, userId: dbUserId });
|
|
|
|
const existingUserQuery = `SELECT * FROM ${dbFullName}.users WHERE id = ?`;
|
|
const existingUserValues = [updatedUserId];
|
|
|
|
const existingUser = (await dbHandler({
|
|
query: existingUserQuery,
|
|
values: existingUserValues,
|
|
database: dbFullName,
|
|
})) as any[];
|
|
|
|
if (!existingUser?.[0]) {
|
|
return {
|
|
success: false,
|
|
msg: "User not found",
|
|
};
|
|
}
|
|
|
|
const data = (() => {
|
|
const reqBodyKeys = Object.keys(payload);
|
|
|
|
const targetTableSchema = (() => {
|
|
try {
|
|
const targetDatabaseSchema = dbSchema?.tables?.find(
|
|
(tbl) => tbl.tableName == "users"
|
|
);
|
|
return targetDatabaseSchema;
|
|
} catch (error) {
|
|
return undefined;
|
|
}
|
|
})();
|
|
|
|
const finalData: { [s: string]: any } = {};
|
|
|
|
reqBodyKeys.forEach((key) => {
|
|
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;
|
|
});
|
|
|
|
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,
|
|
};
|
|
}
|