Skip to content

refactor: implement workspace selection logic and add tests for role-based workspace retrieval - #8285

Merged
wangdan-fit2cloud merged 1 commit into
v3from
pr@v3@refactor_user_workspace
Dec 3, 2026
Merged

wangdan-fit2cloud merged 1 commit into
v3from
pr@v3@refactor_user_workspace

Conversation

@shaohuzhang1

Copy link
Copy Markdown
Contributor

refactor: implement workspace selection logic and add tests for role-based workspace retrieval


assert.equal(getInitialWorkspaceId('workspace-a', workspaces), 'default')
assert.equal(getInitialWorkspaceId(null, undefined), 'default')
})

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 a review of the diff:

Potential Issues

  1. Fragile module stubbing via compileFunction + hard-coded assert.equal(id, ...)

    • The mock resolver asserts that every require() call receives exactly '@/api/enums'. If workspace-selection.ts ever 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)
  2. transpileModule doesn't type-check or resolve imports

    • It only transpiles syntax. Any type errors in workspace-selection.ts are silently ignored by tests. Fine for a runtime unit test, but be aware it won't catch TS mistakes. Consider running tsc --noEmit separately.
  3. 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 .ts extension import path also means this relies on import.meta.url resolution—fine, but worth noting.
  4. Hard-coded Chinese strings in test(...) names — fine if project convention, but the role names (空间管理员) don't affect logic; keep only what's asserted.

  5. Magic value 'default' — the fallback ID is duplicated as a literal in tests. If workspace-selection.ts exports/references a constant (e.g. DEFAULT_WORKSPACE_ID), assert against that instead to avoid drift.

  6. 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_info is undefined / missing.
    • Multiple roles where WORKSPACE_MANAGE is not first in role_info (the third test partially covers, good).
    • Duplicate cached IDs.
    • The getInitialWorkspaceId(null, undefined) case is covered — good.
  7. role_type values duplicated between test fixtures and mock

    • The stub defines ROLE_TYPE, but fixtures use raw strings ('WORKSPACE_MANAGE', 'USER'). If source compares against ROLE_TYPE.X, using the same enum in fixtures would make the intent clearer and catch mismatches.
  8. Mock object shape

    • Returned exports starts as {}; if the compiled module assigns to module.exports directly (not just exports.foo), the destructure const { getInitialWorkspaceId } will be undefined. Currently works because the source presumably uses named exports, but it's brittle. Passing module isn't done here — confirm the source uses ESM-style named exports transpiled to exports.x = ....

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:test hooks 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'
}

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.

Overall, the logic is sound and there are no obvious syntax/type errors. Potential issues and suggestions:

  1. 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/undefined if the caller should handle “no workspace” explicitly.
    • If 'default' is guaranteed to exist, document that assumption.
  2. workspaceList may be undefined while 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”.
  3. 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 | undefined if callers may pass undefined.
  4. Predicate readability

    • workspace.id && hasWorkspaceManagerRole(workspace) works, but the predicate returns string | boolean.
    • Prefer Boolean(workspace.id) && hasWorkspaceManagerRole(workspace) or workspace.id !== '' && ... for clarity.
  5. Role check semantics

    • hasWorkspaceManagerRole only checks role_type. Confirm whether disabled/deleted workspaces or role status also need filtering.
    • Also confirm role_info represents the current user’s roles, not all users’ roles.
  6. Return type assumption

    • The function returns string, so WorkspaceItem.id must be a non-optional string. Verify the type definition.
  7. Minor optimization

    • The two find calls are O(n) each, but this is negligible for typical workspace lists. No change needed unless the list is very large.

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)

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.

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

  1. Fallback chain must be preserved
    The original logic was:

    storedId || firstWorkspaceId || 'default'

    Ensure getInitialWorkspaceId preserves exactly:

    • valid stored ID → stored ID
    • otherwise first workspace ID
    • otherwise 'default'

    If the helper can return undefined/null, selectedWorkspaceId may become invalid.

  2. String vs number ID comparison
    localStorage.getItem() always returns string | null, but workspace_list[].id may be a number. If the helper uses strict comparison:

    workspace.id === storedId

    a stored "1" will not match workspace ID 1. Normalize with String(workspace.id) === storedId, or define a consistent ID type.

  3. Premature validation when workspace list is not loaded
    At setup time, user.userInfo?.workspace_list may still be undefined. 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 present
    • workspaces.length === 0 → loaded but empty, fall back to 'default'
  4. Empty-string stored value
    The original || treated '' as missing. If the helper uses ?? or only checks null, an empty string may be treated as a valid ID. Trim and treat empty string as missing.

  5. 'default' sentinel
    Ensure 'default' is accepted even if it is not present in workspace_list.

  6. 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 as ref<string>(...) or a consistent WorkspaceId union.

  7. Reactivity / initialization timing
    This is a one-time initialization. If user.userInfo loads asynchronously after setup, selectedWorkspaceId will 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.

  8. localStorage access safety
    localStorage.getItem can 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_list undefined, empty workspace_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 localStorage directly.

Overall, the diff is fine structurally; the critical review point is whether getInitialWorkspaceId correctly handles missing workspace data, type mismatches, and the 'default' fallback.

@wangdan-fit2cloud
wangdan-fit2cloud merged commit 4be5dd9 into v3 Dec 3, 2026
3 of 4 checks passed
@wangdan-fit2cloud
wangdan-fit2cloud deleted the pr@v3@refactor_user_workspace branch December 3, 2026 09:22
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.

3 participants