local-store.md 6.72 KB

LocalStore - 本地存储数据库方案

一个灵活、安全、简洁、类数据库的本地存储方案,完美契合 uni-app x 开发需求。

特性

✨ 灵活 - 支持复杂查询、排序、分页等数据库操作
🔒 安全 - 类型安全、数据验证、错误处理
📦 简洁 - API 设计简洁直观,易于使用
🗄️ 类数据库 - 提供索引、批量操作、统计等数据库功能
🚀 高性能 - 优化的存储策略,支持快速查询

安装

将 local-store.uts 文件放入项目的 utils 目录即可。

快速开始

1. 定义数据 Schema

type UserSchema = {
  name: string;
  age: number;
  email: string;
  status: 'active' | 'inactive';
  createdAt: number;
};

2. 创建 Store 实例

import LocalStore from './utils/local-store';

const userStore = new LocalStore<UserSchema>('user', {
  name: '',
  age: 0,
  email: '',
  status: 'active',
  createdAt: 0
});

3. 基础操作

// 插入数据(自动生成 ID)
const id = userStore.insert({
  name: 'Alice',
  age: 25,
  email: 'alice@example.com',
  status: 'active',
  createdAt: Date.now()
});

// 查询数据
const user = userStore.findOne(id);

// 更新数据
userStore.update(id, { age: 26 });

// 删除数据
userStore.delete(id);

API 文档

构造函数

new LocalStore<T>(name: string, schema: T)
  • name: 存储名称(作为命名空间前缀)
  • schema: 数据结构的默认值定义

基础 CRUD

insert(idOrData, data?) - 插入记录

// 自动生成 ID
const id1 = userStore.insert({ name: 'Alice', age: 25 });

// 指定 ID
const id2 = userStore.insert('user_123', { name: 'Bob', age: 30 });

get(id) / findOne(id) - 获取单条记录

const user = userStore.findOne(id);
if (user != null) {
  console.log(user.name);
}

update(id, updates) - 更新记录

userStore.update(id, { age: 26 });

delete(id) - 删除记录

userStore.delete(id);

exists(id) - 检查记录是否存在

if (userStore.exists(id)) {
  console.log('记录存在');
}

查询操作

find(options?) - 查询多条记录

// 简单查询
const users = userStore.find({
  where: {
    age: { $gte: 18 }
  }
});

// 多条件查询
const activeUsers = userStore.find({
  where: {
    status: 'active',
    age: { $gte: 20, $lte: 30 }
  },
  sort: [
    { field: 'age', order: 'desc' }
  ],
  limit: 10,
  skip: 0
});

查询操作符

  • $eq - 等于
  • $ne - 不等于
  • $gt - 大于
  • $gte - 大于等于
  • $lt - 小于
  • $lte - 小于等于
  • $in - 在数组中
  • $nin - 不在数组中
  • $like - 字符串匹配(支持 % 通配符)
  • $exists - 字段是否存在

findFirst(where?) - 查找第一条记录

const firstUser = userStore.findFirst({ status: 'active' });

findAll() - 获取所有记录

const allUsers = userStore.findAll();

count(where?) - 统计记录数量

const total = userStore.count();
const activeCount = userStore.count({ status: 'active' });

批量操作

insertMany(items) - 批量插入

const ids = userStore.insertMany([
  { name: 'Alice', age: 25 },
  { name: 'Bob', age: 30 }
]);

updateMany(where, updates) - 批量更新

const count = userStore.updateMany(
  { status: 'inactive' },
  { status: 'active' }
);

deleteMany(where) - 批量删除

const count = userStore.deleteMany({ age: { $lt: 18 } });

索引操作

createIndex(field) - 创建索引

userStore.createIndex('email');

findByIndex(field, value) - 使用索引查询

const users = userStore.findByIndex('email', 'alice@example.com');

dropIndex(field) - 删除索引

userStore.dropIndex('email');

rebuildIndexes(fields) - 重建索引

userStore.rebuildIndexes(['email', 'status']);

工具方法

clear() - 清空所有记录

userStore.clear();

getStats() - 获取存储统计信息

const stats = userStore.getStats();
console.log(`总记录数: ${stats.total}, 存储大小: ${stats.size} bytes`);

使用示例

示例 1: 用户管理

type UserSchema = {
  name: string;
  email: string;
  age: number;
  createdAt: number;
};

const userStore = new LocalStore<UserSchema>('user', {
  name: '',
  email: '',
  age: 0,
  createdAt: 0
});

// 添加用户
const userId = userStore.insert({
  name: 'Alice',
  email: 'alice@example.com',
  age: 25,
  createdAt: Date.now()
});

// 查询所有成年用户
const adults = userStore.find({
  where: { age: { $gte: 18 } },
  sort: [{ field: 'createdAt', order: 'desc' }]
});

示例 2: 购物车

type CartItemSchema = {
  productId: string;
  productName: string;
  price: number;
  quantity: number;
};

const cartStore = new LocalStore<CartItemSchema>('cart', {
  productId: '',
  productName: '',
  price: 0,
  quantity: 0
});

// 添加商品
cartStore.insert({
  productId: 'prod_001',
  productName: '商品A',
  price: 99.99,
  quantity: 2
});

// 更新数量
const items = cartStore.findAll();
if (items.length > 0) {
  cartStore.update(items[0].id, { quantity: 3 });
}

示例 3: 收藏管理

type FavoriteSchema = {
  userId: string;
  itemId: string;
  itemType: 'article' | 'video';
  createdAt: number;
};

const favoriteStore = new LocalStore<FavoriteSchema>('favorite', {
  userId: '',
  itemId: '',
  itemType: 'article',
  createdAt: 0
});

// 创建索引提高查询性能
favoriteStore.createIndex('userId');

// 查询用户的所有收藏
const favorites = favoriteStore.findByIndex('userId', 'user_123');

注意事项

  1. 类型安全: 确保 Schema 定义完整,所有字段都有默认值
  2. ID 唯一性: 如果手动指定 ID,确保 ID 唯一
  3. 性能考虑: 对于大量数据,建议创建索引以提高查询性能
  4. 存储限制: uni-app 的本地存储有大小限制,注意数据量
  5. 数据迁移: Schema 变更时,需要手动处理数据迁移

最佳实践

  1. 使用索引: 对经常查询的字段创建索引
  2. 批量操作: 大量数据操作时使用批量方法
  3. 错误处理: 使用 try-catch 处理可能的错误
  4. 数据验证: 在插入前验证数据格式
  5. 定期清理: 定期清理过期或无效数据

技术实现

  • 使用 uni.getStorageSync / uni.setStorageSync 进行本地存储
  • 整条记录序列化存储,提高读写效率
  • ID 列表维护,支持快速遍历
  • 索引机制,支持快速查询
  • 类型安全的泛型设计

兼容性

  • ✅ uni-app x
  • ✅ UTS 语言规范
  • ✅ 所有平台(App、H5、小程序)

许可证

MIT