deepbase
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseDeepBase
DeepBase
Overview
概述
DeepBase is a multi-driver persistence system for Node.js that provides a unified API across storage backends (JSON, SQLite, MongoDB, Redis, IndexedDB). It allows switching or combining backends without changing application code.
Use this skill when:
- Adding persistence to a Node.js project
- Setting up multi-backend storage with automatic failover
- Migrating data between storage drivers
- Working with nested object paths for data access
- Integrating any DeepBase driver package
Do NOT use this skill when:
- The project needs a full ORM or relational query builder (use Prisma, Drizzle, etc.)
- The project requires SQL queries, joins, or complex aggregations
- The task is about browser-only storage without DeepBase (use raw IndexedDB/localStorage)
DeepBase是一款适用于Node.js的多驱动持久化系统,可在多种存储后端(JSON、SQLite、MongoDB、Redis、IndexedDB)间提供统一API。它支持在不修改应用代码的情况下切换或组合不同后端。
在以下场景使用本技能:
- 为Node.js项目添加持久化功能
- 配置带自动故障转移的多后端存储
- 在不同存储驱动间迁移数据
- 使用嵌套对象路径进行数据访问
- 集成任意DeepBase驱动包
请勿在以下场景使用本技能:
- 项目需要完整ORM或关系型查询构建器(请使用Prisma、Drizzle等)
- 项目需要SQL查询、关联查询或复杂聚合操作
- 任务仅涉及浏览器端存储且不使用DeepBase(请使用原生IndexedDB/localStorage)
Installation
安装
bash
undefinedbash
undefinedCore package (includes JSON driver by default)
Core package (includes JSON driver by default)
npm install deepbase
npm install deepbase
Optional drivers — install only what you need
Optional drivers — install only what you need
npm install deepbase-sqlite # SQLite (better-sqlite3)
npm install deepbase-mongodb # MongoDB
npm install deepbase-redis # Redis (vanilla)
npm install deepbase-redis-json # Redis Stack (RedisJSON)
npm install deepbase-indexeddb # Browser IndexedDB
The core `deepbase` package depends on `deepbase-json` and `nanoid`. No other drivers are required unless explicitly used.npm install deepbase-sqlite # SQLite (better-sqlite3)
npm install deepbase-mongodb # MongoDB
npm install deepbase-redis # Redis (vanilla)
npm install deepbase-redis-json # Redis Stack (RedisJSON)
npm install deepbase-indexeddb # Browser IndexedDB
核心`deepbase`包依赖`deepbase-json`和`nanoid`。除非明确使用,否则无需安装其他驱动。Imports
导入
javascript
// ES Modules (recommended)
import DeepBase from 'deepbase';
import { DeepBase, DeepBaseDriver } from 'deepbase';
// CommonJS
const { DeepBase } = require('deepbase');
// Individual drivers
import { JsonDriver } from 'deepbase-json';
import { MongoDriver } from 'deepbase-mongodb';
import { SqliteDriver } from 'deepbase-sqlite';
import { RedisDriver } from 'deepbase-redis';
import { RedisDriver as RedisJsonDriver } from 'deepbase-redis-json';
import { IndexedDBDriver } from 'deepbase-indexeddb';javascript
// ES Modules (recommended)
import DeepBase from 'deepbase';
import { DeepBase, DeepBaseDriver } from 'deepbase';
// CommonJS
const { DeepBase } = require('deepbase');
// Individual drivers
import { JsonDriver } from 'deepbase-json';
import { MongoDriver } from 'deepbase-mongodb';
import { SqliteDriver } from 'deepbase-sqlite';
import { RedisDriver } from 'deepbase-redis';
import { RedisDriver as RedisJsonDriver } from 'deepbase-redis-json';
import { IndexedDBDriver } from 'deepbase-indexeddb';Basic Usage
基础用法
Single driver (JSON — simplest setup)
单驱动(JSON — 最简配置)
javascript
import DeepBase from 'deepbase';
const db = new DeepBase({ path: './data', name: 'app' });
await db.connect();
await db.set('config', 'theme', 'dark');
const theme = await db.get('config', 'theme'); // 'dark'
await db.disconnect();Lazy connect is enabled by default — is called automatically on first operation if omitted.
connect()javascript
import DeepBase from 'deepbase';
const db = new DeepBase({ path: './data', name: 'app' });
await db.connect();
await db.set('config', 'theme', 'dark');
const theme = await db.get('config', 'theme'); // 'dark'
await db.disconnect();默认启用延迟连接——如果省略,会在首次操作时自动调用。
connect()Multi-driver with failover
带故障转移的多驱动
javascript
import DeepBase from 'deepbase';
import { JsonDriver } from 'deepbase-json';
import { MongoDriver } from 'deepbase-mongodb';
const db = new DeepBase([
new MongoDriver({ url: 'mongodb://localhost:27017', database: 'myapp', collection: 'data' }),
new JsonDriver({ path: './backup', name: 'fallback' })
], {
writeAll: true, // Write to all drivers (default: true)
readFirst: true, // Read from first available (default: true)
failOnPrimaryError: false // Continue if primary fails
});
await db.connect();
// Writes go to both MongoDB and JSON; reads try MongoDB first, fall back to JSONjavascript
import DeepBase from 'deepbase';
import { JsonDriver } from 'deepbase-json';
import { MongoDriver } from 'deepbase-mongodb';
const db = new DeepBase([
new MongoDriver({ url: 'mongodb://localhost:27017', database: 'myapp', collection: 'data' }),
new JsonDriver({ path: './backup', name: 'fallback' })
], {
writeAll: true, // 写入所有驱动(默认:true)
readFirst: true, // 优先从第一个可用驱动读取(默认:true)
failOnPrimaryError: false // 主驱动故障时继续执行
});
await db.connect();
// 写入操作会同时同步到MongoDB和JSON;读取操作优先尝试MongoDB,失败则回退到JSONAPI Reference
API参考
All methods are async. Path arguments are variadic strings representing nested keys.
所有方法均为异步。路径参数为可变长度字符串,代表嵌套键。
Data operations
数据操作
| Method | Signature | Description |
|---|---|---|
| | Get value at path. Returns |
| | Set value at path. Last argument is the value. |
| | Delete value at path. |
| | Increment numeric value. |
| | Decrement numeric value. |
| | Add item with auto-generated ID. Returns full path array. |
| | Atomic update — passes current value to |
| 方法 | 签名 | 描述 |
|---|---|---|
| | 获取指定路径的值。若未找到则返回 |
| | 设置指定路径的值。最后一个参数为要设置的值。 |
| | 删除指定路径的值。 |
| | 递增数值类型的值。 |
| | 递减数值类型的值。 |
| | 添加带自动生成ID的项。返回完整路径数组。 |
| | 原子更新——将当前值传入 |
Query operations
查询操作
| Method | Signature | Description |
|---|---|---|
| | Get keys at path (array of strings). |
| | Get values at path. |
| | Get |
| | Remove and return the last item. |
| | Remove and return the first item. |
| 方法 | 签名 | 描述 |
|---|---|---|
| | 获取指定路径下的所有键(字符串数组)。 |
| | 获取指定路径下的所有值。 |
| | 获取指定路径下的 |
| | 删除并返回最后一项。 |
| | 删除并返回第一项。 |
Connection
连接管理
| Method | Description |
|---|---|
| Connect all drivers. Returns |
| Disconnect all drivers. |
| 方法 | 描述 |
|---|---|
| 连接所有驱动。返回 |
| 断开所有驱动的连接。 |
Driver access
驱动访问
| Method | Description |
|---|---|
| Get driver instance by index (default: 0). |
| Get array of all driver instances. |
| 方法 | 描述 |
|---|---|
| 通过索引获取驱动实例(默认:0)。 |
| 获取所有驱动实例的数组。 |
Migration
数据迁移
javascript
// Migrate data from driver 0 to driver 1
await db.migrate(0, 1, {
clear: true, // Clear target first (default: true)
batchSize: 100, // Progress callback interval
onProgress: ({ migrated, errors, current }) => console.log(`${migrated} items`)
});
// Sync primary (index 0) to all other drivers
await db.syncAll({ clear: true });javascript
// 将数据从驱动0迁移到驱动1
await db.migrate(0, 1, {
clear: true, // 先清空目标驱动(默认:true)
batchSize: 100, // 进度回调的间隔
onProgress: ({ migrated, errors, current }) => console.log(`${migrated} items`)
});
// 将主驱动(索引0)同步到所有其他驱动
await db.syncAll({ clear: true });Constructor Options
构造函数选项
javascript
new DeepBase(drivers, {
writeAll: true, // Write to all drivers
readFirst: true, // Read from first available driver in order
failOnPrimaryError: true, // Throw if primary driver (index 0) fails
lazyConnect: true, // Auto-connect on first operation
timeout: 0, // Global timeout in ms (0 = disabled)
readTimeout: 0, // Override for read operations
writeTimeout: 0, // Override for write operations
connectTimeout: 0 // Override for connect
});javascript
new DeepBase(drivers, {
writeAll: true, // 写入所有驱动
readFirst: true, // 按顺序从第一个可用驱动读取
failOnPrimaryError: true, // 主驱动(索引0)故障时抛出错误
lazyConnect: true, // 首次操作时自动连接
timeout: 0, // 全局超时时间(毫秒,0表示禁用)
readTimeout: 0, // 覆盖读取操作的超时时间
writeTimeout: 0, // 覆盖写入操作的超时时间
connectTimeout: 0 // 覆盖连接操作的超时时间
});Driver Configuration
驱动配置
| Driver | Key Options |
|---|---|
| |
| |
| |
| |
| |
| |
| 驱动 | 关键选项 |
|---|---|
| |
| |
| |
| |
| |
| |
Agent Usage Rules
Agent使用规则
- Check before installing. Verify for existing
package.jsondependency before runningdeepbase.npm install - Use the official API. Never manipulate driver internals or the underlying JSON/SQLite/Mongo storage directly. Always go through ,
db.get(), etc.db.set() - Prefer lazy connect. Do not call explicitly unless you need the
db.connect()result. Lazy connect handles it automatically.{ connected, total } - Always on shutdown. Especially important for MongoDB and Redis drivers to release connections.
disconnect() - Use for auto-IDs. Do not manually generate IDs with nanoid/uuid —
add()returns the full path array including the generated ID.add() - Spread the path from . The return value is an array: use
add()to retrieve the added item.await db.get(...userPath) - Use for atomic changes. When modifying existing values based on their current state, use
upd()instead ofupd()+get()to avoid race conditions.set() - Set for resilient setups. When using multi-driver for fault tolerance, disable this so operations continue via fallback drivers.
failOnPrimaryError: false - Use environment variables for connection strings. Never hardcode MongoDB URLs or Redis URLs in source code.
- Prefer over
deepbase-redis-jsonwhen working with Redis Stack, as it supports native JSON operations.deepbase-redis
- 安装前检查:运行前,先检查
npm install中是否已存在package.json依赖。deepbase - 使用官方API:切勿直接操作驱动内部或底层的JSON/SQLite/Mongo存储,始终通过、
db.get()等官方方法操作。db.set() - 优先使用延迟连接:除非需要结果,否则不要显式调用
{ connected, total },延迟连接会自动处理。db.connect() - 关闭时务必调用:对于MongoDB和Redis驱动尤其重要,需释放连接资源。
disconnect() - 使用生成自动ID:不要手动用nanoid/uuid生成ID——
add()会返回包含生成ID的完整路径数组。add() - 展开返回的路径:返回值是数组,需使用
add()来获取添加的项。await db.get(...userPath) - 原子更新使用:当基于当前值修改现有数据时,使用
upd()而非upd()+get(),避免竞态条件。set() - 高可用配置设置:当使用多驱动实现容错时,禁用该选项以便故障时通过备用驱动继续操作。
failOnPrimaryError: false - 使用环境变量存储连接字符串:切勿在源代码中硬编码MongoDB或Redis的URL。
- 使用Redis Stack时优先选:它支持原生JSON操作,优于
deepbase-redis-json。deepbase-redis
Common Tasks
常见任务
Store and retrieve nested data
存储和获取嵌套数据
javascript
await db.set('users', 'alice', { name: 'Alice', age: 30 });
await db.set('users', 'alice', 'email', 'alice@example.com');
const user = await db.get('users', 'alice');
// { name: 'Alice', age: 30, email: 'alice@example.com' }javascript
await db.set('users', 'alice', { name: 'Alice', age: 30 });
await db.set('users', 'alice', 'email', 'alice@example.com');
const user = await db.get('users', 'alice');
// { name: 'Alice', age: 30, email: 'alice@example.com' }Add items with auto-generated IDs
添加带自动生成ID的项
javascript
const userPath = await db.add('users', { name: 'Bob', email: 'bob@example.com' });
// userPath = ['users', 'aB3xK9mL2n']
const user = await db.get(...userPath);javascript
const userPath = await db.add('users', { name: 'Bob', email: 'bob@example.com' });
// userPath = ['users', 'aB3xK9mL2n']
const user = await db.get(...userPath);Increment/decrement counters
递增/递减计数器
javascript
await db.set('stats', 'views', 0);
await db.inc('stats', 'views'); // 1
await db.inc('stats', 'views', 10); // 11
await db.dec('stats', 'views', 5); // 6javascript
await db.set('stats', 'views', 0);
await db.inc('stats', 'views'); // 1
await db.inc('stats', 'views', 10); // 11
await db.dec('stats', 'views', 5); // 6Atomic update
原子更新
javascript
await db.upd('user', 'name', name => name.toUpperCase());javascript
await db.upd('user', 'name', name => name.toUpperCase());Iterate over collections
遍历集合
javascript
const userKeys = await db.keys('users');
const userList = await db.values('users');
const userEntries = await db.entries('users'); // [[id, data], ...]javascript
const userKeys = await db.keys('users');
const userList = await db.values('users');
const userEntries = await db.entries('users'); // [[id, data], ...]Pop/shift from collections
从集合中弹出/移除首项
javascript
const last = await db.pop('queue'); // Remove and return last item
const first = await db.shift('queue'); // Remove and return first itemjavascript
const last = await db.pop('queue'); // 删除并返回最后一项
const first = await db.shift('queue'); // 删除并返回第一项Custom JSON serialization (circular references)
自定义JSON序列化(处理循环引用)
javascript
import { JsonDriver } from 'deepbase-json';
import { stringify, parse } from 'flatted';
const db = new DeepBase(new JsonDriver({
path: './data',
name: 'circular',
stringify,
parse
}));javascript
import { JsonDriver } from 'deepbase-json';
import { stringify, parse } from 'flatted';
const db = new DeepBase(new JsonDriver({
path: './data',
name: 'circular',
stringify,
parse
}));Three-tier architecture
三层架构配置
javascript
const db = new DeepBase([
new MongoDriver({ url: process.env.MONGO_URL, database: 'app' }),
new JsonDriver({ path: './backup' }),
new RedisDriver({ url: process.env.REDIS_URL })
], { writeAll: true, failOnPrimaryError: false });javascript
const db = new DeepBase([
new MongoDriver({ url: process.env.MONGO_URL, database: 'app' }),
new JsonDriver({ path: './backup' }),
new RedisDriver({ url: process.env.REDIS_URL })
], { writeAll: true, failOnPrimaryError: false });Extend with a custom driver
扩展自定义驱动
javascript
import { DeepBaseDriver } from 'deepbase';
class MyDriver extends DeepBaseDriver {
async connect() { /* ... */ this._connected = true; }
async disconnect() { /* ... */ }
async get(...args) { /* ... */ }
async set(...args) { /* ... */ }
async del(...args) { /* ... */ }
async inc(...args) { /* ... */ }
async dec(...args) { /* ... */ }
async add(...args) { /* ... */ }
async upd(...args) { /* ... */ }
}All methods listed in must be implemented. , , have default implementations that call .
DeepBaseDriverkeys()values()entries()get()javascript
import { DeepBaseDriver } from 'deepbase';
class MyDriver extends DeepBaseDriver {
async connect() { /* ... */ this._connected = true; }
async disconnect() { /* ... */ }
async get(...args) { /* ... */ }
async set(...args) { /* ... */ }
async del(...args) { /* ... */ }
async inc(...args) { /* ... */ }
async dec(...args) { /* ... */ }
async add(...args) { /* ... */ }
async upd(...args) { /* ... */ }
}必须实现中列出的所有方法。、、有默认实现,会调用。
DeepBaseDriverkeys()values()entries()get()Troubleshooting
故障排除
- — Ensure all drivers in the array are proper driver instances, not plain objects.
All drivers must extend DeepBaseDriver - Operation timed out — Increase ,
timeout, orreadTimeoutin the constructor options.writeTimeout - MongoDB/Redis connection fails silently — Set (default) to surface connection errors, or check
failOnPrimaryError: truereturn value forconnect().{ connected, total } - Data not synced across drivers — Ensure (default). For existing data, use
writeAll: trueordb.migrate().db.syncAll() - Stale reads after failover — The fallback driver may have older data. Use after the primary recovers.
db.syncAll()
- — 确保数组中的所有驱动都是正确的驱动实例,而非普通对象。
All drivers must extend DeepBaseDriver - Operation timed out — 在构造函数选项中增大、
timeout或readTimeout的值。writeTimeout - MongoDB/Redis连接静默失败 — 设置(默认值)以暴露连接错误,或检查
failOnPrimaryError: true返回的connect()结果。{ connected, total } - 数据未在驱动间同步 — 确保(默认值)。对于已有数据,使用
writeAll: true或db.migrate()同步。db.syncAll() - 故障转移后读取到旧数据 — 备用驱动可能存储的是旧数据。主驱动恢复后使用同步数据。
db.syncAll()
References
参考资料
- Repository: https://github.com/clasen/DeepBase
- npm: https://www.npmjs.com/package/deepbase
- Examples: directory in the repository (01 through 12)
examples/ - Monorepo packages: ,
packages/core,packages/driver-json,packages/driver-sqlite,packages/driver-mongodb,packages/driver-redis,packages/driver-redis-jsonpackages/driver-indexeddb
- 仓库地址:https://github.com/clasen/DeepBase
- npm地址:https://www.npmjs.com/package/deepbase
- 示例:仓库中的目录(01至12)
examples/ - 单仓库包:、
packages/core、packages/driver-json、packages/driver-sqlite、packages/driver-mongodb、packages/driver-redis、packages/driver-redis-jsonpackages/driver-indexeddb