@amitkhare/indexed-storage

中文文档
1.2.0发布于 2025/06/13MITTypeScriptESM + CJS零依赖近 30 天下载 1933

用于索引DB的现代本地Storage类API,具有实例和静态API,多存储支持,可配置数据库,增强能力

中文使用文档
文档目录26 节
  1. * 特性
  2. * 安装
  3. 导入
  4. 基本用途
  5. 基于新实例的 API
  6. 多个独立实例
  7. 实例配置选项
  8. 单一数据库中的多层
  9. 实例方法
  10. 后向兼容性
  11. QQ 配置
  12. 启用/ 禁用日志
  13. QQ 可配置数据库设置
  14. API 参考
  15. 核心方法
  16. 批量操作
  17. 多层操作
  18. 使用实例
  19. 申请国
  20. 用户首选项
  21. 缓存数据
  22. 多层应用程序
  23. QQ 错误处理
  24. 从本地Storage迁移
  25. 许可证
  26. 捐款

@amitkhare/ 索引存储

一个现代的,类似于IndexedDB的本地Storage的API,为客户端的数据存储提供了简单而直观的接口,具有增强的能力.

* 特性

  • 类似 API 的本地服务器 - 熟悉情况 setItem(), (中文(简体) ), getItem(), (中文(简体) ), removeItem() 接口
  • 类型保存 - 存储和检索精确值(原始、对象、阵列)
  • Async/等待支持 - 基于现代承诺的API
  • 可配置数据库 - 自定义数据库名称、版本和存储名称
  • 多层支持 - 同一数据库中的多个对象存储
  • 多个数据库实例 - 为不同目的建立单独的数据库
  • 存储特定 API - 个别商店的隔离准入
  • 批量操作 - 立即获得/设置/移动多个项目
  • 可选日志 - 用于调试的可配置控制台记录(默认损坏)
  • 类型脚本准备 - 包含完整类型脚本声明
  • 环境意识 - 易于进行开发、中转和生产

* 安装

npm install @amitkhare/indexed-storage

导入

IndexedStorage支持多种导入模式,以达到最大灵活性:

// Default import
import IndexedStorage from '@amitkhare/indexed-storage';

// Named import  
import { IndexedStorage } from '@amitkhare/indexed-storage';

// Import with utilities
import IndexedStorage, { useStorageManager, useIndexedDB } from '@amitkhare/indexed-storage';

// Named import with utilities
import { IndexedStorage, useStorageManager, useIndexedDB } from '@amitkhare/indexed-storage';

// TypeScript type imports
import { IndexedStorage, type IndexedStorageConfig } from '@amitkhare/indexed-storage';

基本用途

// Store data
await IndexedStorage.setItem('username', 'john_doe');
await IndexedStorage.setItem('count', 42);
await IndexedStorage.setItem('user', { name: 'John', age: 30 });

// Retrieve data
const username = await IndexedStorage.getItem('username'); // 'john_doe'
const count = await IndexedStorage.getItem('count'); // 42
const user = await IndexedStorage.getItem('user'); // { name: 'John', age: 30 }

// Check if item exists
if (await IndexedStorage.hasItem('username')) {
  console.log('Username is stored');
}

// Remove item
await IndexedStorage.removeItem('username');

// Clear all data
await IndexedStorage.clear();

基于新实例的 API

新来的: 创建多个具有不同配置的独立索引集实例 !

多个独立实例

// Create separate storage instances for different purposes
const appStorage = new IndexedStorage({
    dbName: 'MyApp',
    storeName: 'settings',
    logging: true
});

const userStorage = new IndexedStorage({
    dbName: 'UserData',  
    storeName: 'profiles'
});

const cacheStorage = new IndexedStorage({
    dbName: 'Cache',
    storeName: 'temp'
});

// Each instance operates independently
await appStorage.setItem('theme', 'dark');
await userStorage.setItem('currentUser', { id: 123, name: 'John' });
await cacheStorage.setItem('lastSync', Date.now());

实例配置选项

const storage = new IndexedStorage({
    dbName: 'MyDatabase',        // Database name (default: 'IndexedStorage')
    version: 1,                  // Database version (default: 1)
    storeName: 'myStore',        // Default store name (default: 'data')
    storeConfig: {               // Store configuration
        keyPath: 'id',           // Key path for the store
        autoIncrement: true      // Auto-increment keys
    },
    logging: true                // Enable logging (default: false)
});

单一数据库中的多层

// Method 1: Create stores during initialization
const storage = new IndexedStorage({
    dbName: 'ECommerceApp',
    storeName: 'products', // default store
    additionalStores: ['users', 'orders', 'cart'], // create these stores automatically
    storeConfigs: {
        users: { keyPath: 'id', autoIncrement: true },
        orders: { keyPath: 'orderId', autoIncrement: false },
        cart: { keyPath: null, autoIncrement: false }
    }
});

// Method 2: Create stores dynamically
const storage2 = new IndexedStorage({
    dbName: 'MyApp',
    storeName: 'default'
});

await storage2.createStore('users', { keyPath: 'id', autoIncrement: true });
await storage2.createStore('sessions', { keyPath: 'sessionId' });

// Store data in different stores
await storage.setItem('prod1', { name: 'Laptop', price: 999 }, 'products');
await storage.setItem('user1', { name: 'John', email: '[email protected]' }, 'users');
await storage.setItem('order1', { total: 999, items: ['prod1'] }, 'orders');

// Get store-specific API for easier operations
const userStore = storage.getStore('users');
const orderStore = storage.getStore('orders');

await userStore.setItem('user2', { name: 'Jane', email: '[email protected]' });
await orderStore.setItem('order2', { total: 1500, items: ['prod1', 'prod2'] });

// Batch operations across multiple stores
await storage.setMultipleStores({
    products: { 'prod2': { name: 'Mouse', price: 29 } },
    users: { 'user3': { name: 'Bob', email: '[email protected]' } }
});

// Get data from multiple stores
const multiData = await storage.getMultipleStores({
    products: ['prod1', 'prod2'],
    users: ['user1', 'user2']
});

// List all stores
const stores = await storage.listStores();
console.log(stores); // ['products', 'users', 'orders', 'cart']

// Get all data from all stores
const allData = await storage.getAllStoresData();
console.log(allData); // { products: {...}, users: {...}, orders: {...}, cart: {...} }

实例方法

核心业务:

  • setItem(key, value, storeName?) - 存储物品
  • getItem(key, storeName?) - 抢取物品
  • removeItem(key, storeName?) - 删除项目
  • clear(storeName?) - 清除商店里的所有物品

批量操作 :

  • getAllKeys(storeName?) - 拿到所有钥匙
  • getAllValues(storeName?) - 获得所有价值

存储管理 :

  • createStore(name, config?) - 创建新商店
  • deleteStore(name) - 删除商店
  • listStores() - 列出所有商店
  • getStoreInfo(name?) - 获取存储信息
  • getAvailableStores() - 获得现有商店(名单的别名)

多层操作 :

  • getStore(storeName) - 获取特定存储的 API 对象
  • getAllStoresData() - 从所有商店获取数据
  • clearAllStores() - 清除数据库中的所有仓库
  • setMultipleStores(storeData) - 将数据设置在多家商店之间
  • getMultipleStores(storeKeys) - 从多家商店获取数据

数据库管理 :

  • init() - 初始化数据库连接
  • close() - 关闭数据库连接

后向兼容性

最初的静态 API 仍然与新实例 API 并行:

// Static API (legacy) - still works
await IndexedStorage.setItem('key', 'value');

// Instance API (new)
const storage = new IndexedStorage({ dbName: 'MyApp' });
await storage.setItem('key', 'value');

📖 见 实例 API 指南 综合实例和移徙指南.

QQ 配置

启用/ 禁用日志

默认情况下,IndexedStorage默默运行. 您可以启用调试日志 :

// Enable logging for debugging (disabled by default)
IndexedStorage.configure({ enableLogging: true });

// Disable logging
IndexedStorage.configure({ enableLogging: false });

// Check current configuration
const config = IndexedStorage.getConfig();
console.log(config); // { enableLogging: false }

QQ 可配置数据库设置

IndexedStorage 现在支持可配置的IndexedDB设置,允许您自定义不同应用程序和使用大小写的数据库名称,版本,并存储名称.

基本数据库配置

// Configure custom database settings
IndexedStorage.configure({
  enableLogging: true,
  indexedDB: {
    dbName: 'MyApplication',        // Database name (default: 'LocalStorageDB')
    dbVersion: 2,                   // Database version (default: 1)
    storeName: 'appData'            // Object store name (default: 'localStates')
  }
});

// All subsequent operations use the custom configuration
await IndexedStorage.setItem('user-data', { name: 'John' });

多个数据库实例

为不同目的创建单独的数据库实例 :

import { useIndexedDB, useStorageManager } from '@amitkhare/indexed-storage';

// User data database
const userDB = useIndexedDB({
  dbName: 'UserData',
  dbVersion: 1,
  storeName: 'users'
});

// Application cache database
const cacheDB = useIndexedDB({
  dbName: 'AppCache',
  dbVersion: 1,
  storeName: 'cache'
});

// Store data in different databases
await userDB.save('profile', { name: 'John', email: '[email protected]' });
await cacheDB.save('api-data', { response: {...}, timestamp: Date.now() });

多层配置

在同一数据库内使用多个对象存储 :

// Configure with multiple stores in the same database
IndexedStorage.configure({
  enableLogging: true,
  indexedDB: {
    dbName: 'MyApplication',
    dbVersion: 1,
    storeName: 'users',                           // Primary store
    additionalStores: ['cache', 'analytics', 'settings'] // Additional stores
  }
});

// Get store-specific APIs
const userStore = IndexedStorage.getStore('users');
const cacheStore = IndexedStorage.getStore('cache');
const analyticsStore = IndexedStorage.getStore('analytics');

// Use each store independently
await userStore.setItem('profile', { name: 'John' });
await cacheStore.setItem('api-data', { response: 'cached' });
await analyticsStore.setItem('event-1', { action: 'click' });

环境配置

const isDevelopment = process.env.NODE_ENV === 'development';

IndexedStorage.configure({
  enableLogging: isDevelopment,
  indexedDB: {
    dbName: isDevelopment ? 'MyApp_Development' : 'MyApp_Production',
    dbVersion: isDevelopment ? 1 : 2,
    storeName: 'appData'
  }
});

📖 见 可配置数据库指南 综合实例和最佳做法.

📖 见 多层用法示例 用于综合多库实例.

📖 见 移徙指南 用于升级为多存储功能.

API 参考

核心方法

getItem(key)

从存储中获取项目 .

  • 回返情况: 存储值或未找到的无效值

setItem(key, value)

存储一个项目.

  • 支持 : 所有 JSON 可序列数据类型

removeItem(key)

从存储中删除项目.

hasItem(key)

检查存储中是否存在项目 .

  • 回返情况: true 如果密钥存在

clear()

从存储中删除所有项目.

getAllKeys()

从存储取出所有密钥 .

  • 回返情况: 所有密钥的矩阵

length()

获取存储中的项目数量.

批量操作

getMultiple(keys)

一次检索多个项目.

const data = await IndexedStorage.getMultiple(['user', 'settings']);
// Returns: { user: {...}, settings: {...} }

setMultiple(items)

立即储存多件物品.

await IndexedStorage.setMultiple({
  'user': { name: 'John' },
  'settings': { theme: 'dark' }
});

removeMultiple(keys)

立即删除多个项目.

await IndexedStorage.removeMultiple(['temp1', 'temp2']);

多层操作

getStore(storeName)

获得特定商店的API,用于与特定商店合作.

const cacheStore = IndexedStorage.getStore('cache');
await cacheStore.setItem('key', 'value');
const value = await cacheStore.getItem('key');

getAvailableStores()

获取数据库中所有可用的仓库列表 .

const stores = IndexedStorage.getAvailableStores();
console.log(stores); // ['users', 'cache', 'analytics', 'settings']

getAllStoresData()

立刻从所有商店获取所有数据.

const allData = await IndexedStorage.getAllStoresData();
// Returns: { users: [...], cache: [...], analytics: [...] }

clearAllStores()

清除所有商店的所有数据 .

await IndexedStorage.clearAllStores();

使用实例

申请国

// Save application state
await IndexedStorage.setItem('app-state', {
  currentView: 'dashboard',
  sidebarCollapsed: true,
  activeProject: 'project-123'
});

// Restore state on reload
const appState = await IndexedStorage.getItem('app-state');
if (appState) {
  navigateToView(appState.currentView);
  setSidebarState(appState.sidebarCollapsed);
}

用户首选项

// Save user preferences
await IndexedStorage.setItem('user-preferences', {
  theme: 'dark',
  language: 'en',
  notifications: true
});

// Load preferences on app start
const prefs = await IndexedStorage.getItem('user-preferences');
if (prefs) {
  applyTheme(prefs.theme);
  setLanguage(prefs.language);
}

缓存数据

// Cache API responses
await IndexedStorage.setItem('api-cache-users', {
  data: usersData,
  timestamp: Date.now(),
  expires: Date.now() + (1000 * 60 * 60) // 1 hour
});

// Check cache before API call
const cachedUsers = await IndexedStorage.getItem('api-cache-users');
if (cachedUsers && Date.now() < cachedUsers.expires) {
  return cachedUsers.data;
}

多层应用程序

// Configure multi-store database
IndexedStorage.configure({
  indexedDB: {
    dbName: 'TodoApp',
    dbVersion: 1,
    storeName: 'todos',
    additionalStores: ['cache', 'analytics', 'settings']
  }
});

// Use different stores for different purposes
const todoStore = IndexedStorage.getStore('todos');
const cacheStore = IndexedStorage.getStore('cache');
const analyticsStore = IndexedStorage.getStore('analytics');
const settingsStore = IndexedStorage.getStore('settings');

// Store todos
await todoStore.setItem('todo-1', {
  title: 'Buy groceries',
  completed: false,
  createdAt: new Date().toISOString()
});

// Cache API response
await cacheStore.setItem('/api/weather', {
  data: { temperature: 22, condition: 'sunny' },
  timestamp: Date.now(),
  ttl: 300000 // 5 minutes
});

// Track user events
await analyticsStore.setItem('event-' + Date.now(), {
  action: 'todo-created',
  timestamp: Date.now(),
  userAgent: navigator.userAgent
});

// Save app settings
await settingsStore.setItem('app-config', {
  theme: 'dark',
  notifications: true,
  autoSave: true
});

// Get data from all stores
const allData = await IndexedStorage.getAllStoresData();
console.log('All stores data:', allData);

QQ 错误处理

IndexedStorage包括全面的错误处理:

try {
  await IndexedStorage.setItem('large-data', massiveObject);
} catch (error) {
  console.error('Failed to store data:', error);
  // Handle storage quota exceeded, etc.
}

// Check availability before using
if (await IndexedStorage.isAvailable()) {
  // Safe to proceed
} else {
  // Fallback to localStorage or other storage
}

从本地Storage迁移

IndexedStorage设计为以同步操作取代本地Storage:

// localStorage (synchronous)
localStorage.setItem('key', JSON.stringify(data));
const data = JSON.parse(localStorage.getItem('key') || '{}');

// IndexedStorage (asynchronous)
await IndexedStorage.setItem('key', data);
const data = await IndexedStorage.getItem('key');

许可证

麻省理工学院执照 - 看 自由主义 详细文件.

捐款

欢迎捐款! 见 捐款额 准则.

版本与发布记录

@amitkhare/indexed-storage 共发布 4 个版本,首次发布于 2025/06/01;过去 12 个月发布了 0 个版本。

版本发布日期距今
1.2.0latest2025/06/131.4 年前
1.1.02025/06/021.4 年前
1.0.12025/06/011.4 年前
1.0.02025/06/011.4 年前

关于 @amitkhare/indexed-storage 的常见问题

@amitkhare/indexed-storage 是什么?

用于索引DB的现代本地Storage类API,具有实例和静态API,多存储支持,可配置数据库,增强能力

如何安装 @amitkhare/indexed-storage?

在项目目录运行 npm install @amitkhare/indexed-storage,或使用 pnpm add / yarn add / bun add。

@amitkhare/indexed-storage 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@amitkhare/indexed-storage 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@amitkhare/indexed-storage 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=14.0.0。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@amitkhare/indexed-storage 可以商用吗?

@amitkhare/indexed-storage 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@amitkhare/indexed-storage 的下载量有多少?

根据 npm 官方下载统计,@amitkhare/indexed-storage 在 2026/10/06 – 2026/11/04 这 30 天内被下载 1,933 次,日均约 64 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@amitkhare/indexed-storage 还在维护吗?

最新版本 1.2.0 发布于 2025/06/13(1.4 年前);至今共发布 4 个版本,其中过去 12 个月发布了 0 个;首次发布于 2025/06/01。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。