@mznjs/db
v0.0.2
Published
一个用于在 Node.js、浏览器和其他运行时中工作的工具库。
Readme
@mznjs/db 库说明文档
1. 库概述
@mznjs/db 是一个功能丰富的数据库和缓存工具库,专为 Node.js、浏览器和其他运行时环境设计。该库提供了简洁易用的 API,用于执行 MySQL 数据库操作和多驱动缓存管理。
主要特性
- MySQL 数据库操作:提供链式调用的 SQL 构建器,支持查询、插入、更新、删除等操作
- 事务支持:内置事务管理功能,确保数据一致性
- 多驱动缓存:支持 memory、redis、mongodb、mysql 等多种缓存驱动
- 过期时间控制:支持灵活的缓存过期策略
- 数据加密:可选的数据加密存储功能
- 连接池管理:优化数据库连接的使用效率
版本信息
- 版本:0.0.1
- 依赖 Node.js 版本:>= 18.0.0
2. 目录结构
@mznjs/db 采用模块化的目录结构,清晰分离了 MySQL 数据库操作和缓存管理功能。核心代码位于 src 目录,包含以下主要模块:
src/
├── index.ts # 库的主入口文件
├── mysql2/ # MySQL 数据库操作模块
│ ├── MyDatabase.ts # MySQL 数据库操作主类
│ ├── QueryBuilder.ts # SQL 查询构建器
│ ├── constants.ts # 常量定义
│ ├── index.ts # mysql2 模块入口
│ └── types.ts # 类型定义
└── store/ # 缓存管理模块
├── cacheManage.ts # 缓存管理主模块
├── unStorage.ts # unstorage 缓存封装
├── interface.ts # 接口定义
├── config/ # 配置相关
├── libs/ # 核心功能库
└── node/ # 节点环境驱动模块职责
- mysql2 模块:提供完整的 MySQL 数据库操作能力,包括连接管理、查询执行、事务处理等
- store 模块:提供多驱动缓存管理功能,支持不同存储后端,具有过期时间控制和数据加密能力
- libs 目录:包含各个模块的核心功能实现和工具函数
- interface.ts:定义了库的公共接口和类型
3. 系统架构与主流程
@mznjs/db 采用模块化架构设计,各组件之间通过清晰的接口进行交互,保持低耦合高内聚。
核心架构图
┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
│ │ │ │ │ │
│ 用户应用代码 │────▶ db 入口 │────▶ MySQL/Store 模块 │
│ │ │ │ │ │
└─────────────────┘ └─────────────────┘ └─────────┬───────┘
│
┌───────────────┬─────────────┴─────────────┬───────────────┐
│ │ │ │
┌───────▼───────┐ ┌─────▼────────┐ ┌─────▼────────┐ ┌─▼─────────────┐
│ MySQL2 │ │ 内存驱动 │ │ Redis驱动 │ │ MongoDB驱动 │
│ 数据库操作 │ │ (默认) │ │ │ │ │
└───────────────┘ └──────────────┘ └───────────────┘ └───────────────┘主要流程说明
MySQL 操作流程
- 初始化:用户通过配置创建 MyDatabase 实例
- 查询构建:通过链式调用设置表名、查询条件、排序等
- 执行查询:调用 get() 或其他执行方法执行查询
- 结果处理:返回标准化的查询结果
缓存操作流程
- 初始化:用户通过 getCacheManage() 获取缓存实例
- 操作执行:调用 set()、get()、remove() 等方法操作缓存
- 驱动适配:根据配置选择合适的存储驱动
- 过期管理:自动处理缓存过期逻辑
4. 核心功能模块
4.1 MySQL 数据库操作 (mysql2)
MySQL 模块提供了完整的数据库操作功能,通过 MyDatabase 类实现。
主要功能
- 连接管理:支持单连接和连接池两种模式
- SQL 构建:提供链式 API 构建 SQL 查询
- 事务支持:内置事务管理功能
- 错误处理:统一的错误处理和状态码
核心类与方法
MyDatabase 类
主要方法包括:
- 构造函数:初始化数据库连接或连接池
- table():设置操作的表名
- where():设置查询条件
- sort():设置排序参数
- field():设置查询字段
- get():执行查询并返回结果
- add():添加数据
- update():更新数据
- del():删除数据
- transaction():执行事务操作
QueryBuilder 类
负责构建 SQL 语句:
- setTable():设置表名
- setWhere():设置 WHERE 条件
- setSort():设置排序
- setFields():设置查询字段
- setUpdate():设置更新内容
- setInsert():设置插入内容
4.2 缓存管理 (store)
缓存模块提供统一的缓存接口,支持多种存储后端。
主要功能
- 多驱动支持:memory、redis、mongodb、mysql 等
- 过期控制:支持灵活的过期时间设置
- 数据加密:可选的数据加密存储
- 统一接口:提供一致的操作接口
核心接口与方法
CustomStorage 接口
定义了缓存操作的标准方法:
- get(key):获取缓存值
- set(key, value, expires):设置缓存,可选过期时间
- remove(key)/del(key):删除缓存
- clear():清空所有缓存
- exists(key):检查缓存是否存在
- count():获取缓存键数量
- expire(key, expires):设置缓存过期时间
- ttl(key):获取缓存剩余过期时间
getCacheManage() 函数
创建缓存管理实例,根据配置选择合适的驱动。
getDriver() 函数
根据配置获取相应的存储驱动。
5. 核心 API/类/函数
5.1 主要导出对象
export const db = {
mysql2: MyDatabase, // MySQL 数据库操作类
store: getCacheManage, // 缓存管理函数
un: getUnstorageCache // unstorage 缓存实例
}5.2 MySQL 模块核心 API
MyDatabase 类
构造函数
constructor(config: ConnectionConfig | PoolConfig, autoExecute: boolean = true)- 参数:
config:数据库连接配置或连接池配置autoExecute:是否自动执行查询,默认为 true
- 功能:初始化数据库连接或连接池
table()
public table(tableName: string): this- 参数:
tableName:表名
- 返回值:当前实例,支持链式调用
- 功能:设置操作的表名
where()
public where(params: QueryParams): this- 参数:
params:查询条件参数对象
- 返回值:当前实例,支持链式调用
- 功能:设置查询条件
get()
public async get<T = any>(): Promise<QueryResult<T>>- 返回值:查询结果对象,包含 code、msg 和 data 字段
- 功能:执行查询并返回结果
add()
public async add(params: QueryParams): Promise<QueryResult>- 参数:
params:要添加的数据
- 返回值:操作结果
- 功能:添加数据到数据库
update()
public async update(params: QueryParams): Promise<QueryResult>- 参数:
params:要更新的数据
- 返回值:操作结果
- 功能:更新数据库中的数据
del()
public async del(): Promise<QueryResult>- 返回值:操作结果
- 功能:删除数据库中的数据
transaction()
public async transaction<T>(operations: (conn: mysql.Connection) => Promise<T>): Promise<QueryResult<T>>- 参数:
operations:事务操作函数
- 返回值:事务执行结果
- 功能:执行事务操作
5.3 Store 模块核心 API
getCacheManage() 函数
function getCacheManage(config?: Partial<UnstorageOptions>): CustomStorage- 参数:
config:缓存配置选项
- 返回值:CustomStorage 实例
- 功能:获取缓存管理实例
CustomStorage 接口方法
get()
get: (key: string) => Promise<any>- 参数:
key:缓存键
- 返回值:缓存值,不存在或已过期则返回 null
- 功能:获取缓存值
set()
set: (key: string, value: StorageValue, expires?: number | string | { ttl: number | string }) => Promise<void>- 参数:
key:缓存键value:缓存值expires:过期时间(秒、时间字符串或包含 ttl 的对象)
- 功能:设置缓存值,可选设置过期时间
remove()/del()
remove: (key: string) => Promise<void>
del: (key: string) => Promise<void>- 参数:
key:要删除的缓存键
- 功能:删除缓存
exists()
exists: (key: string) => Promise<boolean>- 参数:
key:缓存键
- 返回值:布尔值,表示缓存是否存在
- 功能:检查缓存是否存在
6. 技术栈与依赖
| 依赖项 | 版本 | 用途 | |-------|------|------| | mysql2 | ^3.15.2 | MySQL 数据库连接和操作 | | unstorage | ^1.17.1 | 统一存储接口,支持多驱动 | | ioredis | ^5.8.1 | Redis 客户端,用于缓存驱动 | | mongodb | ^6.20.0 | MongoDB 客户端,用于缓存驱动 | | mysql | ^2.18.1 | MySQL 客户端,用于缓存驱动 | | @mznjs/utils | workspace:^ | 工具函数库,提供加密、时间处理等功能 |
7. 关键模块与典型用例
7.1 MySQL 数据库操作示例
连接数据库
import { db } from '@mznjs/db'
// 创建单连接实例
const mysqlInstance = new db.mysql2({
host: 'localhost',
user: 'root',
password: 'password',
database: 'test_db'
})
// 创建连接池实例
const mysqlPoolInstance = new db.mysql2({
host: 'localhost',
user: 'root',
password: 'password',
database: 'test_db',
connectionLimit: 10 // 连接池大小
})查询数据
// 基本查询
const result = await mysqlInstance.table('users')
.where({ status: 1 })
.sort({ id: 'DESC' })
.get()
// 查询指定字段
const user = await mysqlInstance.table('users')
.field(['id', 'name', 'email'])
.where({ id: 1 })
.get()
// 模糊查询
const searchResult = await mysqlInstance.table('users')
.like([{ field: 'name', value: '张', match: 'top' }])
.get()数据操作
// 添加数据
const addResult = await mysqlInstance.table('users')
.add({
name: '张三',
email: '[email protected]',
status: 1
})
// 更新数据
const updateResult = await mysqlInstance.table('users')
.where({ id: 1 })
.update({
name: '李四',
status: 0
})
// 删除数据
const delResult = await mysqlInstance.table('users')
.where({ id: 1 })
.del()
// 根据ID批量删除
const delByIdsResult = await mysqlInstance.table('users')
.delByIds([1, 2, 3])事务操作
// 执行事务
const transactionResult = await mysqlInstance.transaction(async (conn) => {
// 在事务中执行多个操作
await conn.execute('INSERT INTO users (name) VALUES (?)', ['张三'])
await conn.execute('UPDATE accounts SET balance = balance - 100 WHERE user_id = ?', [1])
return { success: true }
})7.2 缓存管理示例
创建缓存实例
import { db } from '@mznjs/db'
// 使用默认配置(内存驱动)
const cache = db.store()
// 使用Redis驱动
const redisCache = db.store({
driver: 'redis',
driveOpts: {
url: 'redis://localhost:6379'
}
})
// 使用MongoDB驱动
const mongoCache = db.store({
driver: 'mongodb',
driveOpts: {
url: 'mongodb://localhost:27017',
dbName: 'cache_db',
collectionName: 'cache'
}
})缓存操作
// 设置缓存,1小时后过期
await cache.set('user:1', { id: 1, name: '张三' }, '1h')
// 设置永久缓存
await cache.set('config', { appName: 'MyApp' }, 'permanent')
// 获取缓存
const user = await cache.get('user:1')
// 检查缓存是否存在
const exists = await cache.exists('user:1')
// 删除缓存
await cache.remove('user:1')
// 或
await cache.del('user:1')
// 设置缓存过期时间
await cache.expire('user:2', '30m')
// 获取缓存剩余过期时间
const ttl = await cache.ttl('user:1')
// 清空所有缓存
await cache.clear()
// 获取缓存数量
const count = await cache.count()8. 配置、部署与开发
安装
pnpm add @mznjs/db配置选项
MySQL 配置
interface ConnectionConfig {
host: string
user: string
password: string
database: string
port?: number
// 其他 mysql2 连接选项
}
interface PoolConfig extends ConnectionConfig {
connectionLimit: number
// 其他连接池选项
}缓存配置
interface UnstorageOptions {
driver: string | Driver // 驱动名称或自定义驱动实例
timeSuffix?: string // 时间戳后缀
encryptKeys?: string[] // 需要加密的键列表
useItemRaw?: boolean // 是否使用原始项操作
driveOpts?: Record<string, any> // 驱动选项
isEncrypt?: boolean // 是否启用加密
isUnStorage?: boolean // 是否使用 unstorage 默认驱动
}9. 总结与亮点回顾
@mznjs/db 是一个功能全面的数据库和缓存工具库,其主要优势包括:
- 统一接口:提供一致的 API 操作不同的数据库和缓存后端
- 链式调用:MySQL 操作支持流畅的链式调用风格
- 多种驱动:缓存模块支持多种存储后端,适应不同场景需求
- 事务支持:内置事务管理,确保数据一致性
- 过期控制:灵活的缓存过期策略,支持多种时间格式
- 数据加密:可选的数据加密功能,保护敏感信息
该库设计简洁而强大,既适合简单应用场景,也能满足复杂业务需求,是 Node.js 应用中处理数据存储的理想选择。
