From 4750f1945d08f5c5dfd59f3b705a0a260b5139a3 Mon Sep 17 00:00:00 2001 From: Methapon2001 <61303214+Methapon2001@users.noreply.github.com> Date: Thu, 18 Apr 2024 16:32:38 +0700 Subject: [PATCH] fix: error when not sent role --- src/controllers/user-controller.ts | 40 ++++++++++++++++++------------ 1 file changed, 24 insertions(+), 16 deletions(-) diff --git a/src/controllers/user-controller.ts b/src/controllers/user-controller.ts index 2f76cb9..51092fe 100644 --- a/src/controllers/user-controller.ts +++ b/src/controllers/user-controller.ts @@ -344,25 +344,33 @@ export class UserController extends Controller { ); } - let list = await getRoles(); + let userRole: string | undefined; - if (!Array.isArray(list)) throw new Error("Failed. Cannot get role(s) data from the server."); - if (Array.isArray(list)) { - list = list.filter( - (a) => - !["uma_authorization", "offline_access", "default-roles"].some((b) => a.name.includes(b)), - ); - } - const currentRole = await getUserRoles(userId); + if (body.userRole) { + let list = await getRoles(); - const role = list.find((v) => v.id === body.userRole); + if (!Array.isArray(list)) throw new Error("Failed. Cannot get role(s) data from the server."); + if (Array.isArray(list)) { + list = list.filter( + (a) => + !["uma_authorization", "offline_access", "default-roles"].some((b) => + a.name.includes(b), + ), + ); + } + const currentRole = await getUserRoles(userId); - const resultAddRole = role && (await addUserRoles(userId, [role])); + const role = list.find((v) => v.id === body.userRole); - if (!resultAddRole) { - throw new Error("Failed. Cannot set user's role."); - } else { - if (Array.isArray(currentRole)) await removeUserRoles(userId, currentRole); + const resultAddRole = role && (await addUserRoles(userId, [role])); + + if (!resultAddRole) { + throw new Error("Failed. Cannot set user's role."); + } else { + if (Array.isArray(currentRole)) await removeUserRoles(userId, currentRole); + } + + userRole = role.name; } const { provinceId, districtId, subDistrictId, ...rest } = body; @@ -391,7 +399,7 @@ export class UserController extends Controller { include: { province: true, district: true, subDistrict: true }, data: { ...rest, - userRole: role.name, + userRole, code: (lastUserOfType && `${user.code?.slice(0, 3)}${body.userType !== "USER" ? body.userType?.charAt(0) : ""}${(+(lastUserOfType?.code?.slice(-4) || 0) + 1).toString().padStart(4, "0")}`) ||