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 🙏

© 2025 – Pkg Stats / Ryan Hefner

@3mcode/token

v1.0.0

Published

一个功能强大且灵活的Token管理类,支持多种存储方式和自定义配置。

Downloads

16

Readme

TokenManager - 灵活的Token管理工具

一个功能强大且灵活的Token管理类,支持多种存储方式和自定义配置。

特性

  • 🎯 多种存储方式: 支持localStorage、sessionStorage、内存存储和自定义存储
  • 🔧 灵活配置: 可自定义token key名称和存储类型
  • 🔄 自动过期检查: 自动检查token是否过期
  • 定时刷新: 支持定时自动刷新token
  • 🛡️ 类型安全: 完整的TypeScript类型支持
  • 🔄 向后兼容: 保持与旧版本的兼容性

安装

npm install

基本使用

1. 使用默认单例(向后兼容)

import TokenManager from './src/index';

const tokenManager = TokenManager.getInstance();

// 设置token
tokenManager.setToken({
    access_token: 'your-access-token',
    refresh_token: 'your-refresh-token',
    expires_in: 3600
});

// 获取token
const token = tokenManager.getToken();
console.log(token);

2. 创建自定义配置的实例

import { createTokenManager, StorageType } from './src/index';

// 使用sessionStorage
const sessionManager = createTokenManager({
    tokenKey: 'my-session-token',
    storageType: StorageType.SESSION_STORAGE
});

// 使用localStorage,自定义key
const localManager = createTokenManager({
    tokenKey: 'my-local-token',
    storageType: StorageType.LOCAL_STORAGE
});

// 使用内存存储
const memoryManager = createTokenManager({
    tokenKey: 'my-memory-token',
    storageType: StorageType.MEMORY
});

3. 使用预设配置

import { createTokenManager, TokenManagerPresets } from './src/index';

// 使用预设的session配置
const sessionManager = createTokenManager(TokenManagerPresets.session('my-token'));

// 使用预设的内存配置
const memoryManager = createTokenManager(TokenManagerPresets.memory('my-token'));

4. 自定义存储实现

import { createTokenManager, StorageInterface } from './src/index';

class CustomStorage implements StorageInterface {
    private data: Map<string, string> = new Map();
    
    getItem(key: string): string | null {
        return this.data.get(key) || null;
    }
    
    setItem(key: string, value: string): void {
        this.data.set(key, value);
    }
    
    removeItem(key: string): void {
        this.data.delete(key);
    }
}

const customManager = createTokenManager({
    tokenKey: 'custom-token',
    customStorage: new CustomStorage()
});

API 参考

TokenManager 类

静态方法

  • getInstance(): 获取默认单例实例
  • create(config): 创建新的TokenManager实例

实例方法

Token 管理
  • setToken(token): 设置token(自动计算过期时间)
  • setTokenByPayload(token): 设置完整token数据
  • getToken(): 获取token(如果过期返回null)
  • removeToken(): 移除token
实用方法
  • hasValidToken(): 检查是否有有效的token
  • getAccessToken(): 获取访问token
  • getRefreshToken(): 获取刷新token
  • isTokenExpiringSoon(minutes?): 检查token是否即将过期
  • getConfig(): 获取当前配置信息
定时刷新
  • scheduleRefresh(expiresIn, refreshFn): 设置定时刷新
  • clearRefreshTimer(): 清除刷新定时器

配置选项

interface TokenManagerConfig {
    tokenKey?: string;           // token key名称,默认 'ors-token'
    storageType?: StorageType;   // 存储类型,默认 localStorage
    customStorage?: StorageInterface; // 自定义存储实现
}

存储类型

enum StorageType {
    LOCAL_STORAGE = 'localStorage',
    SESSION_STORAGE = 'sessionStorage',
    MEMORY = 'memory'
}

Token 数据结构

interface TokenStorage {
    access_token: string;    // 访问token
    refresh_token: string;   // 刷新token
    expires_in: number;      // 过期秒数
    expire_at: Date;         // 过期时间
}

使用场景

1. 多应用场景

// 主应用使用localStorage
const mainAppManager = createTokenManager({
    tokenKey: 'main-app-token',
    storageType: StorageType.LOCAL_STORAGE
});

// 子应用使用sessionStorage
const subAppManager = createTokenManager({
    tokenKey: 'sub-app-token',
    storageType: StorageType.SESSION_STORAGE
});

2. 测试环境

// 测试时使用内存存储,避免污染localStorage
const testManager = createTokenManager({
    tokenKey: 'test-token',
    storageType: StorageType.MEMORY
});

3. 定时刷新

const manager = createTokenManager({
    tokenKey: 'auto-refresh-token',
    storageType: StorageType.LOCAL_STORAGE
});

// 设置token
manager.setToken({
    access_token: 'token',
    refresh_token: 'refresh-token',
    expires_in: 3600
});

// 设置自动刷新
manager.scheduleRefresh(3600, async () => {
    try {
        const newToken = await refreshTokenAPI();
        manager.setToken(newToken);
        console.log('Token已自动刷新');
    } catch (error) {
        console.error('Token刷新失败:', error);
    }
});

运行示例

# 运行示例代码
npx ts-node example.ts

文件结构

src/frontend/token-manager/
├── src/
│   ├── index.ts          # 主入口文件,只做导出
│   ├── types.ts          # 类型定义
│   ├── storage.ts        # 存储相关实现
│   ├── token-manager.ts  # TokenManager类
│   └── presets.ts        # 预设配置和工具函数
├── example.ts            # 使用示例
└── README.md             # 详细文档

模块说明

  • types.ts: 包含所有TypeScript类型定义
  • storage.ts: 存储相关实现,包括MemoryStorage类和StorageFactory
  • token-manager.ts: 核心TokenManager类实现
  • presets.ts: 预设配置和便捷函数
  • index.ts: 主入口文件,统一导出所有公共API

注意事项

  1. 内存存储: 内存存储的数据在页面刷新后会丢失
  2. sessionStorage: 在同一个标签页中有效,关闭标签页后数据丢失
  3. localStorage: 数据持久化,直到手动清除或过期
  4. 定时刷新: 记得在组件卸载时调用 clearRefreshTimer() 清理定时器
  5. 错误处理: 建议在token操作时添加适当的错误处理