Repository navigation
refactor: implement workspace selection logic and add tests for role-based workspace retrieval - #8285
Conversation
…based workspace retrieval
|
|
||
| assert.equal(getInitialWorkspaceId('workspace-a', workspaces), 'default') | ||
| assert.equal(getInitialWorkspaceId(null, undefined), 'default') | ||
| }) |
There was a problem hiding this comment.
Here's a review of the diff:
Potential Issues
-
Fragile module stubbing via
compileFunction+ hard-codedassert.equal(id, ...)- The mock resolver asserts that every
require()call receives exactly'@/api/enums'. Ifworkspace-selection.tsever imports anything else (even a built-in or an additional utility), all tests break with a confusing assertion failure inside the loader rather than at the actual test site. - Better: use a lookup map and throw a descriptive error for unknown ids:
const modules = { '@/api/enums': { ROLE_TYPE: {...} } } compileFunction(outputText, ['require', 'exports'])((id) => { if (!modules[id]) throw new Error(`Unexpected require: ${id}`) return modules[id] }, exports)
- The mock resolver asserts that every
-
transpileModuledoesn't type-check or resolve imports- It only transpiles syntax. Any type errors in
workspace-selection.tsare silently ignored by tests. Fine for a runtime unit test, but be aware it won't catch TS mistakes. Consider runningtsc --noEmitseparately.
- It only transpiles syntax. Any type errors in
-
Loader runs per-test, re-reading and transpiling the file each time
- Minor perf issue (4 tests × readFileSync + transpile). Extract
loadWorkspaceSelection()once at module scope, or cache the result:let cached function loadWorkspaceSelection() { return cached ??= (/* ...actual work... */) }
- The unused
.tsextension import path also means this relies onimport.meta.urlresolution—fine, but worth noting.
- Minor perf issue (4 tests × readFileSync + transpile). Extract
-
Hard-coded Chinese strings in
test(...)names — fine if project convention, but the role names (空间管理员) don't affect logic; keep only what's asserted. -
Magic value
'default'— the fallback ID is duplicated as a literal in tests. Ifworkspace-selection.tsexports/references a constant (e.g.DEFAULT_WORKSPACE_ID), assert against that instead to avoid drift. -
Missing coverage cases
- Empty array
[]. - Cached ID valid AND is admin space but appears after a non-admin admin-space earlier (ordering).
- Workspace whose
role_infoisundefined/ missing. - Multiple roles where
WORKSPACE_MANAGEis not first inrole_info(the third test partially covers, good). - Duplicate cached IDs.
- The
getInitialWorkspaceId(null, undefined)case is covered — good.
- Empty array
-
role_typevalues duplicated between test fixtures and mock- The stub defines
ROLE_TYPE, but fixtures use raw strings ('WORKSPACE_MANAGE','USER'). If source compares againstROLE_TYPE.X, using the same enum in fixtures would make the intent clearer and catch mismatches.
- The stub defines
-
Mock object shape
- Returned
exportsstarts as{}; if the compiled module assigns tomodule.exportsdirectly (not justexports.foo), the destructureconst { getInitialWorkspaceId }will beundefined. Currently works because the source presumably uses named exports, but it's brittle. Passingmoduleisn't done here — confirm the source uses ESM-style named exports transpiled toexports.x = ....
- Returned
Optimization Suggestions
- Move
loadWorkspaceSelection()to module top-level (or memoize) to transpile once. - Hoist shared fixtures (
workspaceManagerRole,userRole, the workspace arrays) to reduce repetition. - Use
t.before/node:testhooks if setup grows. - Consider testing against the real TS build output (compiled JS) instead of ad-hoc transpile+mock, which would remove the custom loader entirely.
Summary
Logic looks reasonable and the scenarios are sensible. Main risks: the over-strict single-module mock, re-transpiling per test, the duplicated 'default' literal, and slightly thin edge-case coverage. None are blockers, but addressing #1, #3, #5, and adding a couple of edge tests would improve resilience.
| } | ||
|
|
||
| return workspaceList?.find((workspace) => workspace.id && hasWorkspaceManagerRole(workspace))?.id ?? 'default' | ||
| } |
There was a problem hiding this comment.
Overall, the logic is sound and there are no obvious syntax/type errors. Potential issues and suggestions:
-
Magic fallback
'default'- It may not be a real workspace ID. If no workspace is found, callers may receive an invalid ID.
- Prefer a named constant, and consider returning
null/undefinedif the caller should handle “no workspace” explicitly. - If
'default'is guaranteed to exist, document that assumption.
-
workspaceListmay beundefinedwhile loading- The function returns
'default'even when the list has not loaded yet. This can cause an incorrect initial workspace request. - Consider distinguishing “not loaded yet” from “no valid workspace found”.
- The function returns
-
Cached ID validation
if (cachedWorkspaceId)accepts whitespace-only strings. If the value comes from storage, consider trimming/validating it first.- The parameter type could be
string | null | undefinedif callers may passundefined.
-
Predicate readability
workspace.id && hasWorkspaceManagerRole(workspace)works, but the predicate returnsstring | boolean.- Prefer
Boolean(workspace.id) && hasWorkspaceManagerRole(workspace)orworkspace.id !== '' && ...for clarity.
-
Role check semantics
hasWorkspaceManagerRoleonly checksrole_type. Confirm whether disabled/deleted workspaces or role status also need filtering.- Also confirm
role_inforepresents the current user’s roles, not all users’ roles.
-
Return type assumption
- The function returns
string, soWorkspaceItem.idmust be a non-optionalstring. Verify the type definition.
- The function returns
-
Minor optimization
- The two
findcalls are O(n) each, but this is negligible for typical workspace lists. No change needed unless the list is very large.
- The two
Optional refactor:
const DEFAULT_WORKSPACE_ID = 'default'
export function getInitialWorkspaceId(
cachedWorkspaceId: string | null | undefined,
workspaceList?: WorkspaceItem[],
): string {
const normalizedCachedId = cachedWorkspaceId?.trim()
if (normalizedCachedId) {
const cachedWorkspace = workspaceList?.find(({ id }) => id === normalizedCachedId)
if (cachedWorkspace && hasWorkspaceManagerRole(cachedWorkspace)) {
return cachedWorkspace.id
}
}
return (
workspaceList?.find(
(workspace) => Boolean(workspace.id) && hasWorkspaceManagerRole(workspace),
)?.id ?? DEFAULT_WORKSPACE_ID
)
}| ) | ||
| const workspaceOptions = ref<WorkspaceItem[]>([]) | ||
| const loadingView = ref(false) | ||
|
|
There was a problem hiding this comment.
The change is reasonable—it centralizes workspace-ID initialization—but the main risk is the contract of getInitialWorkspaceId. I cannot fully validate it without seeing that helper, so verify the following.
Potential issues
-
Fallback chain must be preserved
The original logic was:storedId || firstWorkspaceId || 'default'
Ensure
getInitialWorkspaceIdpreserves exactly:- valid stored ID → stored ID
- otherwise first workspace ID
- otherwise
'default'
If the helper can return
undefined/null,selectedWorkspaceIdmay become invalid. -
String vs number ID comparison
localStorage.getItem()always returnsstring | null, butworkspace_list[].idmay be a number. If the helper uses strict comparison:workspace.id === storedId
a stored
"1"will not match workspace ID1. Normalize withString(workspace.id) === storedId, or define a consistent ID type. -
Premature validation when workspace list is not loaded
At setup time,user.userInfo?.workspace_listmay still beundefined. If the helper treats that as “empty list” and returns'default', a valid stored workspace ID is discarded. The original code preserved the stored ID regardless of whether the list had loaded. Consider distinguishing:workspaces == null→ list not loaded, preserve stored ID if presentworkspaces.length === 0→ loaded but empty, fall back to'default'
-
Empty-string stored value
The original||treated''as missing. If the helper uses??or only checksnull, an empty string may be treated as a valid ID. Trim and treat empty string as missing. -
'default'sentinel
Ensure'default'is accepted even if it is not present inworkspace_list. -
Type safety of
ref
Check the inferred type of:const selectedWorkspaceId = ref(...)
If the helper returns
string | undefined, or if workspace IDs can be numbers, add an explicit type such asref<string>(...)or a consistentWorkspaceIdunion. -
Reactivity / initialization timing
This is a one-time initialization. Ifuser.userInfoloads asynchronously after setup,selectedWorkspaceIdwill not automatically update. That was also true before, but the new helper may validate against an incomplete list. Make sure the helper does not incorrectly invalidate a stored ID before the list is available. -
localStorageaccess safety
localStorage.getItemcan throw in some environments. This was already present before, but if you are refactoring, consider a safe storage utility.
Suggested helper shape
export function getInitialWorkspaceId(
storedId: string | null,
workspaces?: WorkspaceItem[] | null,
): string {
const stored = storedId?.trim()
if (stored === 'default') return stored
// List not loaded yet: preserve stored ID instead of falling back.
if (workspaces == null) {
return stored || 'default'
}
if (stored && workspaces.some(w => String(w.id) === stored)) {
return stored
}
const firstId = workspaces[0]?.id
return firstId != null ? String(firstId) : 'default'
}If your workspace IDs are numbers and downstream APIs expect numbers, do not blindly convert everything to string; instead define and enforce a consistent WorkspaceId type.
Minor suggestions
- Add tests for: valid stored ID, invalid stored ID, empty string,
null,workspace_listundefined, emptyworkspace_list, numeric IDs, and'default'. - If the project enforces import ordering, check the new import placement against lint rules.
- Consider making the workspace-ID storage/parsing logic fully encapsulated so components do not call
localStoragedirectly.
Overall, the diff is fine structurally; the critical review point is whether getInitialWorkspaceId correctly handles missing workspace data, type mismatches, and the 'default' fallback.
refactor: implement workspace selection logic and add tests for role-based workspace retrieval