Repository navigation
refactor: enhance role information handling across user and workspace APIs - #8187
Conversation
| for user in user_list[:200] | ||
| ] | ||
|
|
||
| class BatchDelete(serializers.Serializer): |
There was a problem hiding this comment.
Here are my observations on the diff:
Potential Issues
-
Inconsistent
role_idsemantics — Inprofile(), when no relation model exists, the fallback setsrole_info = [{"role_id": user.role, "role_name": user.role}], i.e.role_idis a role name. But in the relation branch it'sstr(role.id)(a numeric ID). Similarly inget_user_members, the fallback usesRoleConstants.USER.nameasrole_id. This inconsistency will likely confuse API consumers—clarify whetherrole_idis an ID or a name, or rename the field. -
DictFieldwithoutchild/schema —serializers.ListField(child=serializers.DictField(), ...)only validates that each item is a dict; the innerrole_id/role_namekeys aren't validated. Consider a nested serializer for stronger typing and better generated docs. -
Unused variable — In
_get_user_roles,role_id(fromrelation.role_id) is used both as a mapping key insideuser_role_setting_mapping/workspace_mappingand now to indexuser_role_info_mapping[user_id][str(role_id)]. If two relations map to the same role_id, deduping via dict is fine, but verify behavior matches the previousset-based dedupe (e.g., ordering ofrole_infolist is now non-deterministic from dict iteration order). -
Empty-tuple return signature change —
return {}, {}, {}, {}must stay in sync with the number of unpacked variables. It currently matches (4), but this is fragile; consider returning a namedtuple/dataclass or a dict to avoid silent breakage. -
Ordering in
role_info— The profile version sorts bynot role.internal(internal first), preserving prior ordering intention. In_get_user_roles/get_user_members, ordering is not enforced, so the returnedrole_infoorder differs between endpoints. Consistency across APIs would be desirable. -
N+1 / query concern — The
select_related("role")and.distinct("role_id")usage relies on PostgreSQLDISTINCT ON. This isn't portable to SQLite/MySQL. Not new to this diff, but the refactor leaves it intact.
Minor Notes
- The formatting change around
roles = sorted(...)is clean and reduces repeated generator expression, good. role_infodefault[]in.get(...)calls is safe.- Consider adding
required=False, default=listalso where role_info is set on records even when model absent (currentlyrole_infomay be empty whilerolefalls back to[user.role]—verify UI expectations).
Optimization Suggestions
- Return structured results from
_get_user_roles(named tuple) to avoid positional-unpack mistakes. - Use a typed nested serializer (
RoleInfoSerializer) instead of rawDictField. - Normalize
role_idto always be a string identifier; document it. - Cache/short-circuit
role_infoconstruction only once and deriverole_namefrom it ([r["role_name"] for r in role_info]) to avoid duplicate work.
| role_info: roleInfo, | ||
| role_name: roleInfo.map(({ role_name }) => role_name), | ||
| } | ||
| } |
There was a problem hiding this comment.
Code Review
Correctness Issues
localizeRoleSourcereturn type is unsound. The function mutatesrole_nameinto astring[]derived fromrole_info, but returnsT. If the caller's original object had norole_namefield, or had one with a different shape/meaning, the returned value no longer matchesT. Use an explicit return type instead:
export function localizeRoleSource<T extends RoleDisplaySource>(
source: T,
): T & { role_info: RoleInfo[]; role_name: string[] } | TOr better, narrow RoleDisplaySource so role_name is defined as derived-only (e.g. use Pick<T, 'role_info'> + computed).
-
localizeRoleNameonly checksroleId. Ifrole_idis present but not inROLE_NAME_KEYS, it silently falls back toroleName— that's fine, but note you never attempt translation byrole_nameitself. Confirm that's intended (built-in roles are identified solely by ID). -
Type mismatch of
ROLE_NAME_KEYSkey. It's typedPartial<Record<string, string>>while indexed byROLE_TYPEvalues. Prefer tightening:
const ROLE_NAME_KEYS: Partial<Record<ROLE_TYPE, string>> = { ... }This gives compile-time safety if an enum member is renamed.
role_idmay be optional/undefined onRoleInfo.localizeRoleName(role.role_id, role.role_name)implicitly widensundefined→fine, but verifyRoleInfo.role_idcan be missing; if it's required, drop the| undefinedparam to keep signatures honest.
Optimization / Style
-
Idempotency. Calling
localizeRoleSourcetwice will re-localize already-localized names. For built-in roles this is harmless (id lookup wins), for custom roles it's also harmless, but if any logic ever keys offrole_name, this can surprise. Consider short-circuiting whenrole_infois absent (already handled) and documenting idempotency. -
Avoid unnecessary work. In
localizeRoleInfo, the arrow body allocates a new object per item even when nothing changed. A micro-optimization (probably not worth it unless hot path):
return roleInfo?.map((role) => {
const localized = localizeRoleName(role.role_id, role.role_name)
return localized === role.role_name ? role : { ...role, role_name: localized }
})-
Memoization. If
role_infoarrays are stable references and rendering frequently, memoizing by reference viaWeakMap<RoleInfo[], RoleInfo[]>could help — measure first. -
Returning
sourceunchanged whenrole_infois undefined loses the opportunity to populaterole_namefrom any pre-existingrole_namefield — fine, but ensure consumers don't assumerole_nameis always present after calling. Consider a wrapping type or JSDoc clarifying "ifrole_infois absent,sourceis returned untouched." -
Naming.
localizeRoleSourcedescribes an action; considerwithLocalizedRolesto signal pure transformation. -
t()call inside a loop. Iftisn't memoized, repeated calls per framework render may add up. Many i18n libs cache internally; verify. -
Test coverage. Add tests for: unknown
role_id, emptyrole_infoarray ([]→ returns{...source, role_info: [], role_name: []}, which flipsrole_nameto[]even if previously set — is that desired?), androle_info: undefined.
Edge case: role_info: [] is truthy, so it overwrites role_name with []. If that's unintended, guard with roleInfo && roleInfo.length.
Minor
- No obvious security/mutation issues aside from the returned-object typing. The code doesn't mutate inputs (good).
| } | ||
|
|
||
| export default { deleteUser, getUserManageImportTemplate, getUserManagePage, getUserManageSyncTypes, postUser, postBatchDeleteUsers, postBatchSetUserRoles, postBatchSetUserWorkspaceRoles, postSyncSystemUsers, putUser, putUserPassword } No newline at end of file | ||
| export default { deleteUser, getUserManageImportTemplate, getUserManagePage, getUserManageSyncTypes, postUser, postBatchDeleteUsers, postBatchSetUserRoles, postBatchSetUserWorkspaceRoles, postSyncSystemUsers, putUser, putUserPassword } |
There was a problem hiding this comment.
Here's my review of the changes:
Issues
1. .then() return type mismatch (TypeScript)
getUserManagePage declares an implicit return of Promise<ResponsePage<SystemUser>>, but localizeSystemUser returns SystemUser — verify that localizeRoleSource(...) preserves the same shape; if it returns a different/partial type, TS will error or silently widen.
2. Redundant null handling / order of operations
const localizedUser = localizeRoleSource(systemUser)
if (!systemUser.role_workspace) return localizedUserThis is fine, but note that role_info ?? [] is defensive while role_workspace uses a truthiness check on what looks like an array — prefer .length or explicit == null for consistency with the rest of the codebase.
3. Potential performance concern — mapping role_info into a Map per user
For every user you rebuild a Map from role_info. If role_info is large or the page is large, this is O(users × roles). Acceptable for most UI pages, but consider whether localization could be done more cheaply (e.g., only build the map if role_workspace actually references roles not already localized).
4. Silent fallback can mask bugs
localizedRoleNames.get(role.role_name) ?? role.role_nameNote the key used for the map is role.role_name, and it's also the value being looked up. If two roles share the same role_name but differ by role_id, entries collide and one localization wins arbitrarily. Safer to key by role_id:
const localizedRoleNames = new Map(
(systemUser.role_info ?? []).map((r) => [r.role_id, localizeRoleName(r.role_id, r.role_name)]),
)
...
role_name: localizedRoleNames.get(role.role_id) ?? role.role_name,(only if role_workspace items have role_id — otherwise document why name-based lookup is intended).
5. Type annotation of localizeRoleSource return
It takes a SystemUser but its signature isn't shown here. Make sure it returns the same generic shape (T) so { ...localizedUser, role_workspace: ... } remains a valid SystemUser. A generic helper like localizeRoleSource<T extends SystemUser>(u: T): T would be safer than a fixed return type.
Style / minor
- Missing rationale: the mutation happens in the API layer (
getUserManagePage), which now mixes data-fetching with presentation/localization concerns. Typically localization belongs in a view-model/composable layer or in components. This makes the fetch function non-pure w.r.t. display logic and harder to test. - Trailing newline fix is good.
localizeRoleName(role.role_id, role.role_name)— verify argument order matches the helper's signature; easy to swap accidentally with two similar string params. Consider an options object if this pattern repeats.
Optimization suggestions
- Memoize/deduplicate localization results across users on the same page (roles are shared identifiers).
- If
localizeRoleSourceand therole_workspaceblock both touch the same fields, consolidate into onelocalizeSystemUsercall from a single source module to avoid drift. - Consider returning a dedicated
SystemUserViewtype rather than mutatingSystemUserin the transport layer — makes it obvious where localization applies and prevents accidental reuse of "raw" vs "localized" objects.
Summary
No outright bugs, but the main risks are:
- Possible
role_namecollisions — preferrole_idas map key. - Layer violation — localization in the API request function.
- Return-type clarity — confirm
localizeRoleSourceis generic/preserves the shape. - Minor: consistent null checks and possible per-user
Mapoverhead.
refactor: enhance role information handling across user and workspace APIs