Skip to content

refactor: enhance role information handling across user and workspace APIs - #8187

Merged
wxg0103 merged 1 commit into
v3from
pr@v3@refactor_role_information
Nov 26, 2026
Merged

wxg0103 merged 1 commit into
v3from
pr@v3@refactor_role_information

Conversation

@shaohuzhang1

Copy link
Copy Markdown
Contributor

refactor: enhance role information handling across user and workspace APIs

for user in user_list[:200]
]

class BatchDelete(serializers.Serializer):

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Here are my observations on the diff:

Potential Issues

  1. Inconsistent role_id semantics — In profile(), when no relation model exists, the fallback sets role_info = [{"role_id": user.role, "role_name": user.role}], i.e. role_id is a role name. But in the relation branch it's str(role.id) (a numeric ID). Similarly in get_user_members, the fallback uses RoleConstants.USER.name as role_id. This inconsistency will likely confuse API consumers—clarify whether role_id is an ID or a name, or rename the field.

  2. DictField without child/schema — serializers.ListField(child=serializers.DictField(), ...) only validates that each item is a dict; the inner role_id/role_name keys aren't validated. Consider a nested serializer for stronger typing and better generated docs.

  3. Unused variable — In _get_user_roles, role_id (from relation.role_id) is used both as a mapping key inside user_role_setting_mapping/workspace_mapping and now to index user_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 previous set-based dedupe (e.g., ordering of role_info list is now non-deterministic from dict iteration order).

  4. 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.

  5. Ordering in role_info — The profile version sorts by not role.internal (internal first), preserving prior ordering intention. In _get_user_roles / get_user_members, ordering is not enforced, so the returned role_info order differs between endpoints. Consistency across APIs would be desirable.

  6. N+1 / query concern — The select_related("role") and .distinct("role_id") usage relies on PostgreSQL DISTINCT 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_info default [] in .get(...) calls is safe.
  • Consider adding required=False, default=list also where role_info is set on records even when model absent (currently role_info may be empty while role falls 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 raw DictField.
  • Normalize role_id to always be a string identifier; document it.
  • Cache/short-circuit role_info construction only once and derive role_name from it ([r["role_name"] for r in role_info]) to avoid duplicate work.

@wxg0103
wxg0103 merged commit 3f65cab into v3 Nov 26, 2026
3 of 4 checks passed
@wxg0103
wxg0103 deleted the pr@v3@refactor_role_information branch November 26, 2026 09:38
role_info: roleInfo,
role_name: roleInfo.map(({ role_name }) => role_name),
}
}

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

Correctness Issues

  1. localizeRoleSource return type is unsound. The function mutates role_name into a string[] derived from role_info, but returns T. If the caller's original object had no role_name field, or had one with a different shape/meaning, the returned value no longer matches T. Use an explicit return type instead:
export function localizeRoleSource<T extends RoleDisplaySource>(
  source: T,
): T & { role_info: RoleInfo[]; role_name: string[] } | T

Or better, narrow RoleDisplaySource so role_name is defined as derived-only (e.g. use Pick<T, 'role_info'> + computed).

  1. localizeRoleName only checks roleId. If role_id is present but not in ROLE_NAME_KEYS, it silently falls back to roleName — that's fine, but note you never attempt translation by role_name itself. Confirm that's intended (built-in roles are identified solely by ID).

  2. Type mismatch of ROLE_NAME_KEYS key. It's typed Partial<Record<string, string>> while indexed by ROLE_TYPE values. Prefer tightening:

const ROLE_NAME_KEYS: Partial<Record<ROLE_TYPE, string>> = { ... }

This gives compile-time safety if an enum member is renamed.

  1. role_id may be optional/undefined on RoleInfo. localizeRoleName(role.role_id, role.role_name) implicitly widens undefined→fine, but verify RoleInfo.role_id can be missing; if it's required, drop the | undefined param to keep signatures honest.

Optimization / Style

  1. Idempotency. Calling localizeRoleSource twice 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 off role_name, this can surprise. Consider short-circuiting when role_info is absent (already handled) and documenting idempotency.

  2. 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 }
})
  1. Memoization. If role_info arrays are stable references and rendering frequently, memoizing by reference via WeakMap<RoleInfo[], RoleInfo[]> could help — measure first.

  2. Returning source unchanged when role_info is undefined loses the opportunity to populate role_name from any pre-existing role_name field — fine, but ensure consumers don't assume role_name is always present after calling. Consider a wrapping type or JSDoc clarifying "if role_info is absent, source is returned untouched."

  3. Naming. localizeRoleSource describes an action; consider withLocalizedRoles to signal pure transformation.

  4. t() call inside a loop. If t isn't memoized, repeated calls per framework render may add up. Many i18n libs cache internally; verify.

  5. Test coverage. Add tests for: unknown role_id, empty role_info array ([] → returns {...source, role_info: [], role_name: []}, which flips role_name to [] even if previously set — is that desired?), and role_info: undefined.

Edge case: role_info: [] is truthy, so it overwrites role_name with []. If that's unintended, guard with roleInfo && roleInfo.length.

Minor

  1. 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 }

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 localizedUser

This 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_name

Note 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 localizeRoleSource and the role_workspace block both touch the same fields, consolidate into one localizeSystemUser call from a single source module to avoid drift.
  • Consider returning a dedicated SystemUserView type rather than mutating SystemUser in 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:

  1. Possible role_name collisions — prefer role_id as map key.
  2. Layer violation — localization in the API request function.
  3. Return-type clarity — confirm localizeRoleSource is generic/preserves the shape.
  4. Minor: consistent null checks and possible per-user Map overhead.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants