npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

alita-ui-commons

v1.0.5

Published

Alita前端通用能力库 - 权限管理、全局提示、请求封装等

Readme

@alita/ui-commons

Alita前端通用能力库,提供权限管理、全局提示、请求封装等通用功能。

特性

🚀 全局错误提示 - 自动处理权限错误、网络错误等,使用Antd组件显示
🔐 权限管理 - 完整的角色和操作权限检查系统
📡 请求封装 - 增强的fetch封装,支持超时、错误处理、全局配置
React Hooks - 权限、请求、存储等常用Hooks
🛠️ 工具函数 - 常用的工具函数集合

安装

npm install @alita/ui-commons
# 或
yarn add @alita/ui-commons

快速开始

1. 初始化配置

import { requestManager, permissionManager } from '@alita/ui-commons';

// 配置请求管理器
requestManager.setConfig({
  baseURL: 'https://api.example.com',
  timeout: 30000,
  showErrorMessage: true, // 自动显示错误提示
  headers: {
    'Content-Type': 'application/json',
  },
});

// 设置当前用户(通常在登录后)
permissionManager.setUser({
  id: 1,
  username: 'admin',
  roles: ['admin', 'user'],
  permissions: [
    { id: 1, name: '用户管理', url: '/api/users', methodType: 'GET' },
    { id: 2, name: '创建用户', url: '/api/users', methodType: 'POST' },
  ]
});

2. 使用请求功能

import { get, post, put, del } from '@alita/ui-commons';

// GET请求
const users = await get('/users');

// POST请求
const newUser = await post('/users', { 
  name: 'John', 
  email: '[email protected]' 
});

// PUT请求  
const updatedUser = await put('/users/1', { name: 'Jane' });

// DELETE请求
await del('/users/1');

// 自定义配置
await get('/users', {
  showErrorMessage: false, // 不显示错误提示
  showSuccessMessage: true, // 显示成功提示
  successMessage: '获取用户列表成功!'
});

3. 权限检查

import { hasPermission, hasRole, requirePermission } from '@alita/ui-commons';

// 检查权限
const result = hasPermission('/api/users', 'POST');
if (result.hasPermission) {
  // 有权限
} else {
  console.log(result.reason); // 权限不足的原因
}

// 检查角色
if (hasRole('admin')) {
  // 是管理员
}

// 要求权限(会抛出异常)
try {
  requirePermission('/api/users', 'DELETE');
  // 有权限,继续执行
} catch (error) {
  // 没有权限
}

4. 使用React Hooks

import { usePermission, useAuth, useRequest } from '@alita/ui-commons';

function UserManagement() {
  // 权限检查Hook
  const { hasPermission, reason } = usePermission('/api/users', 'POST');
  
  // 认证状态Hook
  const { user, isAuthenticated, logout } = useAuth();
  
  // 请求Hook
  const { data: users, loading, error, refetch } = useRequest('/api/users');

  if (!hasPermission) {
    return <div>权限不足: {reason}</div>;
  }

  return (
    <div>
      {loading && <div>加载中...</div>}
      {error && <div>错误: {error.message}</div>}
      {users && (
        <ul>
          {users.map(user => <li key={user.id}>{user.name}</li>)}
        </ul>
      )}
    </div>
  );
}

5. 全局通知

import { 
  showSuccess, 
  showError, 
  showWarning, 
  showPermissionError,
  showAuthError 
} from '@alita/ui-commons';

// 成功提示
showSuccess('操作成功!');

// 错误提示
showError('操作失败', '请检查网络连接');

// 权限错误提示
showPermissionError('您没有删除用户的权限');

// 认证错误提示
showAuthError('登录已过期,请重新登录');

API 文档

请求管理

requestManager

主要的请求管理器实例。

// 设置全局配置
requestManager.setConfig({
  baseURL: string;
  timeout: number;
  showErrorMessage: boolean;
  showSuccessMessage: boolean;
  headers: Record<string, string>;
});

// 执行请求
requestManager.request<T>(url: string, config?: RequestConfig): Promise<T>
requestManager.get<T>(url: string, config?: RequestConfig): Promise<T>
requestManager.post<T>(url: string, data?: any, config?: RequestConfig): Promise<T>
requestManager.put<T>(url: string, data?: any, config?: RequestConfig): Promise<T>
requestManager.delete<T>(url: string, config?: RequestConfig): Promise<T>

便捷方法

request<T>(url: string, config?: RequestConfig): Promise<T>
get<T>(url: string, config?: RequestConfig): Promise<T>
post<T>(url: string, data?: any, config?: RequestConfig): Promise<T>
put<T>(url: string, data?: any, config?: RequestConfig): Promise<T>
del<T>(url: string, config?: RequestConfig): Promise<T>
patch<T>(url: string, data?: any, config?: RequestConfig): Promise<T>

权限管理

permissionManager

主要的权限管理器实例。

// 用户管理
permissionManager.setUser(user: User | null): void
permissionManager.getUser(): User | null
permissionManager.clearUser(): void

// 认证检查
permissionManager.isAuthenticated(): boolean

// 角色检查
permissionManager.hasRole(roleName: string): boolean
permissionManager.hasAnyRole(roleNames: string[]): boolean
permissionManager.hasAllRoles(roleNames: string[]): boolean

// 权限检查
permissionManager.hasPermission(url: string, method?: string): PermissionCheckResult
permissionManager.requirePermission(url: string, method?: string): void
permissionManager.requireRole(roleName: string): void
permissionManager.requireAuth(): void

通知管理

notificationManager

全局通知管理器。

notificationManager.success(message: string, description?: string): void
notificationManager.error(message: string, description?: string): void
notificationManager.warning(message: string, description?: string): void
notificationManager.info(message: string, description?: string): void
notificationManager.permissionError(message?: string): void
notificationManager.authError(message?: string): void

React Hooks

usePermission

权限检查Hook。

const { hasPermission, reason, user } = usePermission(url: string, method?: string);

useRole

角色检查Hook。

const { hasRole, user } = useRole(roleName: string);

useAuth

认证状态Hook。

const { user, isAuthenticated, updateUser, logout } = useAuth();

useRequest

请求Hook。

const { data, loading, error, execute, refetch } = useRequest<T>(
  url: string, 
  config?: RequestConfig,
  dependencies?: any[]
);

工具函数

常用的工具函数,包括:

  • 类型检查:isString, isNumber, isBoolean, isObject, isArray, isEmpty
  • 函数工具:debounce, throttle
  • 对象工具:deepClone
  • 格式化:formatFileSize, formatTime, formatRelativeTime
  • URL工具:parseQueryString, buildQueryString
  • 数组工具:unique, groupBy
  • Cookie工具:getCookie, setCookie, deleteCookie
  • 其他:generateId, downloadFile, copyToClipboard

错误处理

库会自动处理以下错误并显示相应提示:

  • 401 Unauthorized: 显示认证错误,自动跳转到登录页
  • 403 Forbidden: 显示权限错误提示
  • 404 Not Found: 显示资源不存在提示
  • 500 Internal Server Error: 显示服务器错误提示
  • 网络错误: 显示网络连接失败提示
  • 请求超时: 显示请求超时提示

TypeScript 支持

本库使用TypeScript编写,提供完整的类型定义。

兼容性

  • React >= 16.8.0
  • Antd >= 5.0.0
  • 现代浏览器(支持ES2020)

贡献

欢迎提交Issue和Pull Request。

许可证

MIT