local-store.example.uts
5.32 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
/**
* 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;
}