local-store.example.uts 5.32 KB
/**
 * LocalStore 使用示例
 *
 * 展示如何使用 LocalStore 进行本地数据存储和管理
 */

import LocalStore from "./local-store";

// ===== 1. 定义数据 Schema =====

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

// ===== 2. 创建 Store 实例 =====

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

// ===== 3. 基础 CRUD 操作 =====

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

// 插入数据(指定 ID)
const userId2 = userStore.insert("user_123", {
	name: "Bob",
	age: 30,
	email: "bob@example.com",
	status: "active",
	createdAt: Date.now(),
	updatedAt: Date.now()
});

// 查询单条记录
const user = userStore.findOne(userId1);
if (user != null) {
	console.log("用户信息:", user.name, user.age);
}

// 更新记录
userStore.update(userId1, {
	age: 26,
	updatedAt: Date.now()
});

// 删除记录
userStore.delete(userId2);

// ===== 4. 查询操作 =====

// 简单查询:查找所有年龄大于等于 18 的用户
const adults = userStore.find({
	where: {
		age: { $gte: 18 }
	}
});

// 多条件查询:查找活跃且年龄在 20-30 之间的用户
const youngActiveUsers = userStore.find({
	where: {
		status: "active",
		age: { $gte: 20, $lte: 30 }
	}
});

// 字符串匹配查询:查找邮箱包含 'example' 的用户
const exampleUsers = userStore.find({
	where: {
		email: { $like: "%example%" }
	}
});

// 数组查询:查找年龄在指定列表中的用户
const specificAges = userStore.find({
	where: {
		age: { $in: [25, 30, 35] }
	}
});

// 排序和分页
const sortedUsers = userStore.find({
	where: {
		status: "active"
	},
	sort: [
		{ field: "age", order: "desc" },
		{ field: "createdAt", order: "asc" }
	],
	skip: 0,
	limit: 10
});

// ===== 5. 批量操作 =====

// 批量插入
const newUsers = [
	{
		name: "Charlie",
		age: 28,
		email: "charlie@example.com",
		status: "active" as const,
		createdAt: Date.now(),
		updatedAt: Date.now()
	},
	{
		name: "David",
		age: 32,
		email: "david@example.com",
		status: "active" as const,
		createdAt: Date.now(),
		updatedAt: Date.now()
	}
];
const insertedIds = userStore.insertMany(newUsers);

// 批量更新:将所有非活跃用户的状态改为活跃
const updatedCount = userStore.updateMany(
	{ status: "inactive" },
	{ status: "active", updatedAt: Date.now() }
);

// 批量删除:删除所有年龄小于 18 的用户
const deletedCount = userStore.deleteMany({ age: { $lt: 18 } });

// ===== 6. 索引操作 =====

// 创建索引(提高查询性能)
userStore.createIndex("email");
userStore.createIndex("status");

// 使用索引查询
const usersByEmail = userStore.findByIndex("email", "alice@example.com");
const activeUsers = userStore.findByIndex("status", "active");

// 删除索引
userStore.dropIndex("email");

// 重建索引(数据迁移后使用)
userStore.rebuildIndexes(["email", "status"]);

// ===== 7. 统计和工具方法 =====

// 统计记录数量
const totalUsers = userStore.count();
const activeUserCount = userStore.count({ status: "active" });

// 查找第一条记录
const firstUser = userStore.findFirst({ status: "active" });

// 获取所有记录
const allUsers = userStore.findAll();

// 检查记录是否存在
const exists = userStore.exists(userId1);

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

// 清空所有记录
// userStore.clear();

// ===== 8. 错误处理示例 =====

try {
	// 尝试插入已存在的 ID
	userStore.insert("user_123", {
		name: "Test",
		age: 20,
		email: "test@example.com",
		status: "active",
		createdAt: Date.now(),
		updatedAt: Date.now()
	});
} catch (error) {
	console.error("插入失败:", error);
}

// ===== 9. 实际应用场景 =====

// 场景1:用户收藏管理
type FavoriteSchema = {
	userId: string;
	itemId: string;
	itemType: "article" | "video" | "product";
	createdAt: number;
};

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

// 添加收藏
const favoriteId = favoriteStore.insert({
	userId: "user_123",
	itemId: "article_456",
	itemType: "article",
	createdAt: Date.now()
});

// 查询用户的所有收藏
const userFavorites = favoriteStore.find({
	where: {
		userId: "user_123"
	},
	sort: [{ field: "createdAt", order: "desc" }]
});

// 场景2:购物车管理
type CartItemSchema = {
	productId: string;
	productName: string;
	price: number;
	quantity: number;
	addedAt: number;
};

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

// 添加商品到购物车
cartStore.insert({
	productId: "prod_001",
	productName: "商品A",
	price: 99.99,
	quantity: 2,
	addedAt: Date.now()
});

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

// 计算购物车总价
let totalPrice = 0;
for (let i = 0; i < cartItems.length; i++) {
	totalPrice += cartItems[i].price * cartItems[i].quantity;
}