createTokenManagerRuntime
桥接 useTokenManager 与 createApiClient:注册实例、等待刷新、附加 Bearer、供路由守卫判断登录态。
前置依赖
依赖参数
| 参数名 | 类型 | 说明 |
|---|---|---|
deps.localStorage | Pick<Storage,'getItem'> | null | 冷启动回退读 access 物理键 |
deps.setTimeout | function | 轮询 isRefreshing |
deps.Headers | 构造器 | 附加 Authorization |
deps.accessStorageKey | string | 如 AUTH_STORAGE_KEY_ACCESS |
函数签名
typescript
function createTokenManagerRuntime(
deps: CreateTokenManagerRuntimeDeps,
): TokenManagerRuntime返回值
| 方法 | 说明 |
|---|---|
registerTokenManager | 应用启动时注册 useTokenManager 实例 |
waitForPendingTokenRefresh | 供 createApiClient 在请求前等待 |
createAuthRequestInit | 附加 Bearer |
hasStoredAccessToken | 路由守卫:内存优先,回退 localStorage |
应用侧示例
typescript
import { AUTH_STORAGE_KEY_ACCESS } from 'zcw-shared/constants/authStorage'
import { createTokenManagerRuntime } from 'zcw-shared/functions/auth/createTokenManagerRuntime'
export const tokenRuntime = createTokenManagerRuntime({
localStorage: typeof window !== 'undefined' ? window.localStorage : null,
setTimeout: globalThis.setTimeout.bind(globalThis),
Headers,
accessStorageKey: AUTH_STORAGE_KEY_ACCESS,
})