{"_id":"@aaj/db-help","_rev":"5-e7c28c410dff1e268e0f8c91a5fc19e1","name":"@aaj/db-help","dist-tags":{"latest":"0.1.3"},"versions":{"0.0.1":{"name":"@aaj/db-help","version":"0.0.1","keywords":["indexdb"],"author":{"name":"sturat"},"license":"MIT","_id":"@aaj/db-help@0.0.1","maintainers":[{"name":"aaj","email":"wqiosa@163.com"}],"dist":{"shasum":"97d36a256c2f87f198a6752a08461e39962ab991","tarball":"https://registry.npmjs.org/@aaj/db-help/-/db-help-0.0.1.tgz","fileCount":3,"integrity":"sha512-B5/zKKulCFPCFrCzookHi9H1J0pTf6ATubzvXYHmxpCvvMYSEhIU9r09Thk+4Ucr1QC1MSBj1Z02kwjd6bS/1w==","signatures":[{"sig":"MEYCIQChUmBt0YYkgN4m6X+UBVVFR9txQSWoVpm79Bad/86aGgIhANk6NxXi8OqnqhnfYyhHmf4k8OIlcNEpaqpmizZucJS9","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"unpackedSize":8216},"main":"dist/index.js","types":"dist/index.d.ts","gitHead":"5507ad45d8336e9f15d4152af89ad7bfd3566f7e","scripts":{"build":"tsc"},"_npmUser":{"name":"aaj","email":"wqiosa@163.com"},"_npmVersion":"10.9.2","description":"indexdb help","directories":{},"_nodeVersion":"22.14.0","publishConfig":{"access":"public"},"_hasShrinkwrap":false,"devDependencies":{"typescript":"^5.8.3"},"_npmOperationalInternal":{"tmp":"tmp/db-help_0.0.1_1747743464261_0.5713663772861539","host":"s3://npm-registry-packages-npm-production"}},"0.1.0":{"name":"@aaj/db-help","version":"0.1.0","keywords":["indexdb"],"author":{"name":"sturat"},"license":"MIT","_id":"@aaj/db-help@0.1.0","maintainers":[{"name":"aaj","email":"wqiosa@163.com"}],"dist":{"shasum":"e7c58dff0636f73577ae220d671f1d511baa957d","tarball":"https://registry.npmjs.org/@aaj/db-help/-/db-help-0.1.0.tgz","fileCount":4,"integrity":"sha512-f6Nt5OuyD5eKdOusAJhUY7PareOztNZfB+2skcYhpPagbpjqtP5u9LLAsApsFDf2HR3cH7VvNy/sQyx3vcwzKQ==","signatures":[{"sig":"MEUCIQDvi1Re/lljiQpQHQJ8WBTMNRklnr7IfsMUpHyhxQxDCAIgMIzIoMclW300LRF3D39rv0hR3B4t195AYEDooApJznY=","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"unpackedSize":29776},"main":"dist/index.js","types":"dist/index.d.ts","gitHead":"8b79027d7b0b175a5fb7e53d7f089d6c908ec46f","scripts":{"build":"tsc","publish":"npm publish --registry='https://registry.npmjs.org' --access public"},"_npmUser":{"name":"aaj","email":"wqiosa@163.com"},"_npmVersion":"10.9.2","description":"indexdb help","directories":{},"_nodeVersion":"22.14.0","publishConfig":{"access":"public"},"_hasShrinkwrap":false,"devDependencies":{"typescript":"^5.8.3"},"_npmOperationalInternal":{"tmp":"tmp/db-help_0.1.0_1747803837710_0.05296254379923537","host":"s3://npm-registry-packages-npm-production"}},"0.1.1":{"name":"@aaj/db-help","version":"0.1.1","keywords":["indexdb"],"author":{"name":"sturat"},"license":"MIT","_id":"@aaj/db-help@0.1.1","maintainers":[{"name":"aaj","email":"wqiosa@163.com"}],"dist":{"shasum":"c4a99f66295c377ab50fc0d5d4586f659127cbc0","tarball":"https://registry.npmjs.org/@aaj/db-help/-/db-help-0.1.1.tgz","fileCount":4,"integrity":"sha512-IB6wSnsGfDsIXJTzmpY1DYpUTr4xjHZMEnqWBWcXfdA6lAa3MtzQz6wMsmm+4uPdvCwHWAGlXlHwr9YUM6G5OQ==","signatures":[{"sig":"MEUCIASbvhl53aBY9oLev9al7U+JvNuPK4x77bX6LmtLQbGBAiEAucoQk85rSqwloOR1FPz1nlRP74J/twXvsLtVfCwSBQc=","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"unpackedSize":31478},"main":"dist/index.js","types":"dist/index.d.ts","gitHead":"d0e5489c4ae905e66d7cc7ab4fdc3ceb32006b68","scripts":{"pub":"npm publish --registry='https://registry.npmjs.org'","build":"tsc"},"_npmUser":{"name":"aaj","email":"wqiosa@163.com"},"_npmVersion":"10.9.2","description":"indexdb help","directories":{},"_nodeVersion":"22.14.0","publishConfig":{"access":"public"},"_hasShrinkwrap":false,"devDependencies":{"typescript":"^5.8.3"},"_npmOperationalInternal":{"tmp":"tmp/db-help_0.1.1_1749726994639_0.4393699724975537","host":"s3://npm-registry-packages-npm-production"}},"0.1.2":{"name":"@aaj/db-help","version":"0.1.2","keywords":["indexdb"],"author":{"name":"sturat"},"license":"MIT","_id":"@aaj/db-help@0.1.2","maintainers":[{"name":"aaj","email":"wqiosa@163.com"}],"dist":{"shasum":"160c7c0485ec77868baa7f515a746889d31c8f87","tarball":"https://registry.npmjs.org/@aaj/db-help/-/db-help-0.1.2.tgz","fileCount":4,"integrity":"sha512-DhAc1OOk1Ou4k+aium0PU/a5xXYELi4kjaW6ERpTstjBE+qxFDd/9xP7z0mm/L9YWKF5z/0WpkqodKTeTDO38Q==","signatures":[{"sig":"MEUCIQDk32aw8AzjT7PpaUTA15rqt1DmCOzonTSZRm1nPXG3HAIgb+aozyJukk8MCik5EN/JpcJ0PRYrXSflB0m+10ER6xU=","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"unpackedSize":34794},"main":"dist/index.js","types":"dist/index.d.ts","gitHead":"94108cdcf6e6c210128ed11d194a1004e316c5ee","scripts":{"pub":"npm publish --registry='https://registry.npmjs.org'","build":"tsc"},"_npmUser":{"name":"aaj","email":"wqiosa@163.com"},"_npmVersion":"10.9.2","description":"indexdb help","directories":{},"_nodeVersion":"22.14.0","publishConfig":{"access":"public"},"_hasShrinkwrap":false,"devDependencies":{"typescript":"^5.8.3"},"_npmOperationalInternal":{"tmp":"tmp/db-help_0.1.2_1760663727881_0.7346819393245556","host":"s3://npm-registry-packages-npm-production"}},"0.1.3":{"name":"@aaj/db-help","version":"0.1.3","description":"indexdb help","main":"dist/index.js","types":"dist/index.d.ts","scripts":{"build":"tsc","pub":"npm publish --registry='https://registry.npmjs.org'"},"keywords":["indexdb"],"author":{"name":"sturat"},"license":"MIT","devDependencies":{"typescript":"^5.8.3"},"publishConfig":{"access":"public"},"gitHead":"298d9dd628cbc19b1c291d619b0960c7388d1ea4","_id":"@aaj/db-help@0.1.3","_nodeVersion":"25.1.0","_npmVersion":"11.6.2","dist":{"integrity":"sha512-jLVQB5F6ykVEeCTkYVyrCYoX644HElP4crjnpOIvhB2k+FPuijKdebC9MWyqw7xogqoBcALJw0+swicJR/7SOA==","shasum":"a28deb58fa87451d5d41a83e46f1bd8259d006e3","tarball":"https://registry.npmjs.org/@aaj/db-help/-/db-help-0.1.3.tgz","fileCount":4,"unpackedSize":33885,"signatures":[{"keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U","sig":"MEQCIByL6QHVgPCQuUX/NYo3+40ppYbjaQhdGa1tyvNEKFlxAiB23UbmDLcPYvpLwKkJBnswSF/O261a+d2cx/6/0s7OHw=="}]},"_npmUser":{"name":"aaj","email":"wqiosa@163.com"},"directories":{},"maintainers":[{"name":"aaj","email":"wqiosa@163.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages-npm-production","tmp":"tmp/db-help_0.1.3_1764064001247_0.9556348403803845"},"_hasShrinkwrap":false}},"time":{"created":"2025-05-20T12:17:44.151Z","modified":"2025-11-25T09:46:41.615Z","0.0.1":"2025-05-20T12:17:44.443Z","0.1.0":"2025-05-21T05:03:57.898Z","0.1.1":"2025-06-12T11:16:34.836Z","0.1.2":"2025-10-17T01:15:28.077Z","0.1.3":"2025-11-25T09:46:41.417Z"},"author":{"name":"sturat"},"license":"MIT","keywords":["indexdb"],"description":"indexdb help","maintainers":[{"name":"aaj","email":"wqiosa@163.com"}],"readme":"# DB Help - IndexDB 辅助工具\n\n## 简介\n`db-help` 是一个基于 IndexedDB 的 TypeScript 封装库，\n提供了简单易用的 API 用于操作浏览器本地数据库，支持数据库\n创建、数据增删改查等常见操作。\n\n---\n\n## 安装\n```bash\nnpm install @aaj/db-help\n```\n## 快速开始\n### 1. 配置数据库\n首先定义数据库配置对象 `DBConfig` ，包含以下字段：\n\n- `name` : 数据库名称（必填）\n- `version` : 数据库版本（必填，需为整数）\n- `stores` : 存储对象（Object Store）配置数组（必填），每个存储对象包含：\n  - `name` : 存储对象名称（必填）\n  - `keyPath` : 数据的键路径（可选，字符串或字符串数组）\n  - `autoIncrement` : 是否自增主键（可选，布尔值）\n  - `indexes` : 其它的索引值（可选）\n    - `name` : 索引名称（必填）\n    - `keyPath` : 索引键路径（必填）\n    - `unique` : 是否唯一索引（可选，布尔值）\n\n示例配置：\n```typescript\nconst dbConfig: DBConfig = {\n    name: \"MyAppDB\",\n    version: 1,\n    stores: [\n        {\n            name: \"users\",\n            keyPath: \"id\",\n            autoIncrement: false,\n            indexes: [\n                { name: \"nameIndex\", keyPath: \"name\", unique: false },  // 按姓名索引（非唯一）\n                { name: \"emailIndex\", keyPath: \"email\", unique: true }   // 按邮箱索引（唯一）\n            ]\n        }\n    ]\n};\n```\n\n## 索引优先操作\n### 使用索引获取数据\n通过指定`indexName`参数，可优先使用索引查询数据（适用于唯一索引）：\n```typescript\n// 通过邮箱索引获取用户（唯一索引）\nconst user = await dbWrapper.get(\"users\", \"user@example.com\", \"emailIndex\");\n```\n\n### 使用索引更新数据\n对于非唯一索引，需先通过索引获取主键，再更新数据：\n```typescript\n// 通过姓名索引更新用户信息（非唯一索引需处理可能的多条数据）\nconst users = await dbWrapper.getByIndexAll(\"users\", \"nameIndex\", \"John\");\nif (users.length > 0) {\n    const updatedUser = { ...users[0], age: 30 };\n    await dbWrapper.put(\"users\", updatedUser, \"nameIndex\");\n}\n```\n\n### 使用索引删除数据\n通过索引定位并删除数据：\n```typescript\n// 通过邮箱索引删除用户（唯一索引）\nawait dbWrapper.delete(\"users\", \"user@example.com\", \"emailIndex\");\n```\n\n### 注意事项\n- 索引操作需确保索引已在`DBConfig`中配置，否则会抛出错误\n- 唯一索引（`unique: true`）使用`get`方法可直接获取单条数据，非唯一索引需使用`getByIndexAll`获取多条\n- 通过索引更新/删除时，若未找到对应主键会抛出\"未通过索引找到对应的主键\"错误\n\n### 2. 初始化数据库\n通过 `IndexDBWrapper` 类初始化实例，并调用 `open()` 方法打开数据库：\n```typescript\nimport { IndexDBWrapper } from \"@aaj/db-help\";\nconst dbWrapper = new IndexDBWrapper(dbConfig);\nlet dbInstance;\n\ntry {\n  dbInstance = await dbWrapper.open();\n  console.log('数据库打开成功:', dbInstance);\n} catch (error) {\n  console.error('数据库打开失败:', error);\n}\n```\n\n### 3. 数据操作\n#### 插入数据(`add`)\n- 无索引：直接插入数据，主键由keyPath或autoIncrement决定\n- 有索引：插入时会自动更新关联索引（无需额外传index参数，索引由DBConfig配置自动维护）\n\n示例：\n```typescript\nconst newUser = { id: 1, name: 'Alice', age: 30 };\nconst userId = await dbWrapper.add('users', newUser); // 无索引插入\nconsole.log('插入的用户ID:', userId);\n```\n\n#### 查询数据(`get`)\n- 无索引：传入存储对象名称和键值（keyPath对应的值）查询数据\n- 有索引（仅适用于唯一索引）：传入存储对象名称、索引键值和索引名称查询数据\n\n示例：\n```typescript\n// 无索引：通过键值查询（keyPath为\"id\"）\nconst userById = await dbWrapper.get('users', 1);\nconsole.log('通过键值查询到的用户:', userById);\n\n// 有索引（唯一索引）：通过邮箱索引查询\nconst userByEmail = await dbWrapper.get('users', 'user@example.com', 'emailIndex');\nconsole.log('通过索引查询到的用户:', userByEmail);\n```\n\n#### 通过索引获取所有数据(`getByIndexAll`)\n- 适用于非唯一索引，传入存储对象名称、索引名称和索引键值，获取所有匹配数据\n\n示例：\n```typescript\n// 通过姓名索引（非唯一）获取所有名为\"John\"的用户\nconst johnUsers = await dbWrapper.getByIndexAll('users', 'nameIndex', 'John');\nconsole.log('通过非唯一索引查询到的用户列表:', johnUsers);\n```\n\n#### 通过索引获取单个数据(`getByIndex`)\n- 适用于唯一索引，传入存储对象名称、索引名称和索引键值，获取单个匹配数据\n\n示例：\n```typescript\n// 通过邮箱索引（唯一）获取特定邮箱的用户\nconst userByEmail = await dbWrapper.getByIndex('users', 'emailIndex', 'user@example.com');\nconsole.log('通过唯一索引查询到的用户:', userByEmail);\n```\n\n#### 通过索引范围获取数据(`getAllByIndexRange`)\n- 传入存储对象名称、索引名称和键范围（IDBKeyRange），获取范围内所有匹配数据\n\n示例：\n```typescript\n// 假设已配置年龄索引ageIndex（keyPath: 'age', unique: false）\nconst ageRange = IDBKeyRange.bound(25, 35); // 年龄范围25到35\nconst usersInAgeRange = await dbWrapper.getAllByIndexRange('users', 'ageIndex', ageRange);\nconsole.log('年龄在25到35岁之间的用户:', usersInAgeRange);\n```\n\n#### 更新数据(`put`)\n- 无索引：传入存储对象名称和完整数据（需包含keyPath值）更新数据\n- 有索引（非唯一索引需先获取主键）：传入存储对象名称、新数据和索引名称更新数据\n\n示例：\n```typescript\n// 无索引：通过键值更新\nconst updatedUser = { id: 1, name: 'Alice Smith', age: 31 };\nconst updateResult = await dbWrapper.put('users', updatedUser);\nconsole.log('更新的用户ID:', updateResult);\n\n// 有索引（非唯一索引）：先通过索引获取主键再更新\nconst users = await dbWrapper.getByIndexAll('users', 'nameIndex', 'John');\nif (users.length > 0) {\n    const updatedUser = { ...users[0], age: 30 };\n    const updateResult = await dbWrapper.put('users', updatedUser, 'nameIndex'); // 传入索引名称\n    console.log('通过索引更新的用户ID:', updateResult);\n    }\n```\n\n#### 增量更新数据(`incrementalUpdate`)\n- 传入存储对象名称、键值（keyPath对应的值）和部分数据（Partial<T>）更新部分字段\n\n示例：\n```typescript\n// 增量更新用户年龄（仅更新age字段）\nconst updateResult = await dbWrapper.incrementalUpdate('users', 1, { age: 32 });\nconsole.log('增量更新的用户ID:', updateResult);\n```\n\n#### 删除数据(`delete`)\n- 无索引：传入存储对象名称和键值（keyPath对应的值）删除数据\n- 有索引（仅适用于唯一索引）：传入存储对象名称、索引键值和索引名称删除数据\n\n示例：\n```typescript\n// 无索引：通过键值删除\nawait dbWrapper.delete('users', 1);\nconsole.log('用户删除成功');\n\n// 有索引（唯一索引）：通过邮箱索引删除\nawait dbWrapper.delete('users', 'user@example.com', 'emailIndex');\nconsole.log('通过索引删除用户成功');\n```\n#### 清空存储对象(`clear`)\n```typescript\nawait dbWrapper.clear('users');\nconsole.log('用户存储对象已清空');\n```\n#### 获取所有数据(`getAll`)\n```typescript\nconst allUsers = await dbWrapper.getAll('users');\nconsole.log('所有用户:', allUsers);\n```\n### 4. 关闭数据库\n```typescript\ndbWrapper.close();\nconsole.log('数据库已关闭');\n```\n### 5. 销毁数据库\n```typescript\ndbWrapper.deleteDB();\nconsole.log('数据库已销毁');\n```\n\n## API 文档\n### `IndexDBWrapper` 类\n#### 构造函数\n`constructor(config: DBConfig)`\n- `config`: 数据库配置对象\n  - `name`: 数据库名称（string）\n  - `version`: 数据库版本（number）\n  - `stores`: 对象存储配置数组\n    - `name`: 存储名称（string）\n    - `keyPath?`: 键路径（string | string[]）\n    - `autoIncrement?`: 自动递增（boolean）\n\n#### 核心方法\n| 方法名       | 参数                  | 返回值                  | 说明                 |\n|--------------|-----------------------|-------------------------|----------------------|\n| `open()`      | -                     | `Promise<IDBDatabase>`  | 打开/初始化数据库    |\n| `add()`       | `storeName: string`, `data: T` | `Promise<IDBValidKey>` | 插入新数据（索引由DBConfig自动维护，无需额外传index参数）           |\n| `get()`       | `storeName: string`, `key: IDBValidKey`, `indexName?: string` | `Promise<T \\| undefined>` | 根据键或索引查询数据：无索引时使用键值（keyPath对应值）；有索引时（仅适用于唯一索引）使用索引键值和索引名称       |\n| `put()`       | `storeName: string`, `data: T`, `indexName?: string` | `Promise<IDBValidKey>` | 更新现有数据：无索引时需包含keyPath值；有索引时（非唯一索引需先获取主键）使用索引名称定位主键       |\n| `delete()`    | `storeName: string`, `key: IDBValidKey`, `indexName?: string` | `Promise<void>`        | 根据键或索引删除数据：无索引时使用键值；有索引时（仅适用于唯一索引）使用索引键值和索引名称       |\n| `clear()`     | `storeName: string`   | `Promise<void>`         | 清空存储所有数据     |\n| `getAll()`    | `storeName: string`   | `Promise<T[]>`          | 获取存储所有数据     |\n| `incrementalUpdate()` | `storeName: string`, `key: IDBValidKey`, `partialData: Partial<T>` | `Promise<IDBValidKey>` | 增量更新部分字段（仅更新传入的部分数据） |\n| `getAllByIndexRange()` | `storeName: string`, `indexName: string`, `range: IDBKeyRange` | `Promise<T[]>` | 通过索引范围获取所有匹配数据 |\n| `getByIndexAll()` | `storeName: string`, `indexName: string`, `key: IDBValidKey` | `Promise<T[]>` | 通过索引获取所有匹配数据（适用于非唯一索引） |\n| `getByIndex()` | `storeName: string`, `indexName: string`, `key: IDBValidKey` | `Promise<T | undefined>` | 通过索引获取单个匹配数据（适用于唯一索引） |\n| `close()`     | -                     | `void`                  | 关闭数据库连接       |\n| `deleteDB()`  | -                     | `void`                  | 销毁整个数据库       |\n\n## 注意事项\n- 数据库版本升级时，需通过 `setConfig` 更新版本号并重新调用 `open()` ，\n  此时会触发 `onupgradeneeded` 事件，可在此事件中执行存储对象的迁移操作。\n- 所有数据操作需在数据库打开（`open` 成功）后执行，否则会抛出 `数据库未打开` 错误。\n- IndexedDB 操作是异步的，需通过 `Promise` 或 `async/await` 处理结果。\n- 确保数据库配置对象 `DBConfig` 正确定义，否则可能导致数据库初始化失败。\n- 索引修改限制 ：`IndexDB` 不支持直接修改索引的 `keyPath` 或 `unique` 属性，因此若需修改索引配置（如将 `unique` 从 `false` 改为 `true` ），需通过升级数据库版本（ `version` 递增）触发 `onupgradeneeded` 事件，先删除旧索引再创建新索引。\n- 性能影响 ：索引会增加数据写入/更新的开销（需同步更新索引），建议仅对需要频繁查询的字段添加索引。\n\n## 贡献\n欢迎提交Issue或Pull Request，共同完善工具库功能！","readmeFilename":"README.md"}