Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 | 4x 4x 4x 4x 4x 3x 3x 3x 2x 2x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 18x 18x 18x 18x 18x 43x 43x 43x 18x 18x 18x 2x 2x 2x 1x 1x 1x 6x 6x 6x 6x 6x 6x 2x 2x 2x 1x 1x 1x 18x 6x 6x 6x 1x 1x 2x 3x 3x 3x 2x 4x 5x 32x 32x 4x 71x 4x 4x 4x 4x 4x 4x 4x 4x | /**
* 猫粮状态管理 Store
*
* 功能特性:
* - 规范化数据存储(以ID为key的对象)
* - 智能缓存策略(避免重复请求)
* - 持久化支持(AsyncStorage)
* - 分页管理
* - 搜索功能
* - 乐观更新
* - 完善的错误处理
*
* @module catFoodStore
*/
import { useMemo } from 'react';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { create } from 'zustand';
import { createJSONStorage, persist } from 'zustand/middleware';
import { supabaseCatfoodService } from '@/src/lib/supabase';
import type { CatFood } from '@/src/types/catFood';
import { logger } from '@/src/utils/logger';
// ==================== 类型定义 ====================
/**
* 分页信息
*/
interface PaginationInfo {
page: number;
pageSize: number;
total: number;
hasMore: boolean;
}
/**
* 列表类型
*/
type ListType = 'all' | 'search' | 'favorites';
/**
* 缓存元数据
*/
interface CacheMetadata {
timestamp: number;
expiresIn: number; // 缓存过期时间(毫秒)
}
/**
* 猫粮状态接口
*/
interface CatFoodState {
// ==================== 数据状态 ====================
/**
* 规范化的猫粮数据存储(以ID为key)
* 好处:O(1)查找,避免数据重复,便于更新
*/
entities: Record<number, CatFood>;
/**
* 不同列表的ID数组
* 分离数据和列表顺序,便于管理
*/
lists: {
all: number[]; // 全部列表
search: number[]; // 搜索结果
favorites: number[]; // 收藏列表
};
/**
* 分页信息
*/
pagination: Record<ListType, PaginationInfo>;
/**
* 缓存元数据
*/
cacheMetadata: Record<number, CacheMetadata>;
// ==================== UI 状态 ====================
/**
* 加载状态
*/
isLoading: boolean;
/**
* 刷新状态
*/
isRefreshing: boolean;
/**
* 加载更多状态
*/
isLoadingMore: boolean;
/**
* 错误信息
*/
error: string | null;
/**
* 水化状态
*/
_hasHydrated: boolean;
// ==================== 数据操作 ====================
/**
* 获取猫粮列表
* @param page 页码(从1开始)
* @param refresh 是否刷新(清空现有数据)
*/
fetchCatFoods: (page?: number, refresh?: boolean) => Promise<void>;
/**
* 获取单个猫粮详情
* @param id 猫粮ID
* @param forceRefresh 强制刷新(忽略缓存)
*/
fetchCatFoodById: (id: number, forceRefresh?: boolean) => Promise<CatFood>;
/**
* 搜索猫粮
* @param query 搜索关键词
* @param page 页码
*/
searchCatFoods: (query: string, page?: number) => Promise<void>;
/**
* 加载更多
* @param listType 列表类型
*/
loadMore: (listType?: ListType) => Promise<void>;
/**
* 更新猫粮数据(乐观更新)
* @param id 猫粮ID
* @param data 要更新的数据
*/
updateCatFood: (id: number, data: Partial<CatFood>) => void;
/**
* 批量添加猫粮到store
* @param catfoods 猫粮数组
* @param listType 添加到哪个列表
*/
addCatFoods: (catfoods: CatFood[], listType?: ListType) => void;
/**
* 批量更新多个猫粮(用于实时同步)
* @param updates 更新数组
*/
batchUpdateCatFoods: (updates: { id: number; data: Partial<CatFood> }[]) => void;
// ==================== 缓存管理 ====================
/**
* 检查缓存是否有效
* @param id 猫粮ID
*/
isCacheValid: (id: number) => boolean;
/**
* 清除过期缓存
*/
clearExpiredCache: () => void;
/**
* 清除所有缓存
*/
clearAllCache: () => void;
// ==================== 工具方法 ====================
/**
* 根据ID获取猫粮
* @param id 猫粮ID
*/
getCatFoodById: (id: number) => CatFood | undefined;
/**
* 获取指定列表的猫粮数组
* @param listType 列表类型
*/
getCatFoodsByList: (listType?: ListType) => CatFood[];
/**
* 设置加载状态
*/
setLoading: (loading: boolean) => void;
/**
* 设置错误信息
*/
setError: (error: string | null) => void;
/**
* 设置水化状态
*/
setHasHydrated: (hasHydrated: boolean) => void;
/**
* 重置状态
*/
reset: () => void;
}
// ==================== 常量配置 ====================
/**
* 缓存配置
*/
const CACHE_CONFIG = {
DEFAULT_EXPIRE: 5 * 60 * 1000, // 5分钟
DETAIL_EXPIRE: 10 * 60 * 1000, // 10分钟
LIST_EXPIRE: 3 * 60 * 1000, // 3分钟
};
/**
* 默认分页配置
*/
const DEFAULT_PAGE_SIZE = 20;
/**
* 初始分页信息
*/
const INITIAL_PAGINATION: PaginationInfo = {
page: 0,
pageSize: DEFAULT_PAGE_SIZE,
total: 0,
hasMore: true,
};
// ==================== Store 实现 ====================
export const useCatFoodStore = create<CatFoodState>()(
persist(
(set, get) => ({
// ==================== 初始状态 ====================
entities: {},
lists: {
all: [],
search: [],
favorites: [],
},
pagination: {
all: { ...INITIAL_PAGINATION },
search: { ...INITIAL_PAGINATION },
favorites: { ...INITIAL_PAGINATION },
},
cacheMetadata: {},
isLoading: false,
isRefreshing: false,
isLoadingMore: false,
error: null,
_hasHydrated: false,
// ==================== 数据获取 ====================
/**
* 获取猫粮列表
*/
fetchCatFoods: async (page = 1, refresh = false) => {
const state = get();
// 防止重复请求
if (state.isLoading && !refresh) {
logger.debug('正在加载中,跳过重复请求');
return;
}
try {
// 设置加载状态
if (refresh) {
set({ isRefreshing: true, error: null });
} else {
set({ isLoading: true, error: null });
}
logger.info('获取猫粮列表', { page });
// 调用 Supabase API
const { data, error } = await supabaseCatfoodService.listCatfoods({
page,
pageSize: DEFAULT_PAGE_SIZE,
});
if (error) {
throw new Error(error.message);
}
if (!data || !Array.isArray(data)) {
throw new Error('响应数据格式异常');
}
const results = data;
const count = data.length;
const next = data.length === DEFAULT_PAGE_SIZE ? 'has_more' : null;
// 更新entities(规范化存储)
const newEntities = { ...state.entities };
const newIds: number[] = [];
const timestamp = Date.now();
results.forEach((catfood) => {
newEntities[catfood.id] = catfood;
newIds.push(catfood.id);
// 更新缓存元数据
state.cacheMetadata[catfood.id] = {
timestamp,
expiresIn: CACHE_CONFIG.LIST_EXPIRE,
};
});
// 更新列表(追加或替换)
const updatedList = refresh || page === 1 ? newIds : [...state.lists.all, ...newIds];
// 去重
const uniqueList = Array.from(new Set(updatedList));
set({
entities: newEntities,
lists: {
...state.lists,
all: uniqueList,
},
pagination: {
...state.pagination,
all: {
page,
pageSize: DEFAULT_PAGE_SIZE,
total: count,
hasMore: next !== null,
},
},
cacheMetadata: { ...state.cacheMetadata },
});
logger.info('成功加载猫粮数据', { count: results.length });
} catch (error) {
const errorMsg = error instanceof Error ? error.message : '获取猫粮列表失败';
logger.error('获取猫粮列表失败', error as Error);
set({ error: errorMsg });
throw error;
} finally {
set({ isLoading: false, isRefreshing: false });
}
},
/**
* 获取单个猫粮详情
*/
fetchCatFoodById: async (id: number, forceRefresh = false): Promise<CatFood> => {
const state = get();
// 检查缓存
const cachedItem = state.entities[id];
if (!forceRefresh && cachedItem && state.isCacheValid(id)) {
logger.debug('使用缓存数据', { id });
return cachedItem;
}
try {
set({ isLoading: true, error: null });
logger.info('获取猫粮详情', { id });
const { data, error } = await supabaseCatfoodService.getCatfoodDetail(String(id));
if (error || !data) {
throw new Error(error?.message || '获取猫粮详情失败');
}
const catfood = data as CatFood;
// 更新entity
const newEntities: Record<number, CatFood> = { ...state.entities, [id]: catfood };
// 更新缓存元数据
const newMetadata = {
...state.cacheMetadata,
[id]: {
timestamp: Date.now(),
expiresIn: CACHE_CONFIG.DETAIL_EXPIRE,
},
};
set({
entities: newEntities,
cacheMetadata: newMetadata,
});
logger.info('成功获取猫粮详情', { name: catfood.name });
return catfood;
} catch (error) {
const errorMsg = error instanceof Error ? error.message : '获取猫粮详情失败';
logger.error('获取猫粮详情失败', error as Error);
set({ error: errorMsg });
throw error;
} finally {
set({ isLoading: false });
}
},
/**
* 搜索猫粮
*/
searchCatFoods: async (query: string, page = 1) => {
const state = get();
if (!query.trim()) {
logger.warn('搜索关键词为空');
set({
lists: { ...state.lists, search: [] },
pagination: {
...state.pagination,
search: { ...INITIAL_PAGINATION },
},
});
return;
}
try {
set({ isLoading: true, error: null });
logger.info('搜索猫粮', { query, page });
const { data, error } = await supabaseCatfoodService.listCatfoods({
search: query,
page,
pageSize: DEFAULT_PAGE_SIZE,
});
if (error) {
throw new Error(error.message);
}
if (!data || !Array.isArray(data)) {
throw new Error('搜索响应数据格式异常');
}
const results = data;
const count = data.length;
const next = data.length === DEFAULT_PAGE_SIZE ? 'has_more' : null;
// 更新entities
const newEntities = { ...state.entities };
const newIds: number[] = [];
const timestamp = Date.now();
results.forEach((catfood) => {
newEntities[catfood.id] = catfood;
newIds.push(catfood.id);
state.cacheMetadata[catfood.id] = {
timestamp,
expiresIn: CACHE_CONFIG.LIST_EXPIRE,
};
});
// 更新搜索列表
const updatedSearchList = page === 1 ? newIds : [...state.lists.search, ...newIds];
set({
entities: newEntities,
lists: {
...state.lists,
search: Array.from(new Set(updatedSearchList)),
},
pagination: {
...state.pagination,
search: {
page,
pageSize: DEFAULT_PAGE_SIZE,
total: count,
hasMore: next !== null,
},
},
cacheMetadata: { ...state.cacheMetadata },
});
logger.info('搜索成功', { resultCount: results.length });
} catch (error) {
const errorMsg = error instanceof Error ? error.message : '搜索猫粮失败';
logger.error('搜索猫粮失败', error as Error);
set({ error: errorMsg });
throw error;
} finally {
set({ isLoading: false });
}
},
/**
* 加载更多
*/
loadMore: async (listType: ListType = 'all') => {
const state = get();
const pagination = state.pagination[listType];
if (!pagination.hasMore || state.isLoadingMore) {
logger.debug('没有更多数据或正在加载中');
return;
}
try {
set({ isLoadingMore: true, error: null });
const nextPage = pagination.page + 1;
logger.info('加载更多', { listType, page: nextPage });
if (listType === 'all') {
await get().fetchCatFoods(nextPage, false);
} else if (listType === 'search') {
// 需要保存搜索关键词以支持加载更多
logger.warn('搜索列表的加载更多需要提供搜索关键词');
}
logger.info('加载更多成功');
} catch (error) {
logger.error('加载更多失败', error as Error);
} finally {
set({ isLoadingMore: false });
}
},
/**
* 更新猫粮数据(乐观更新 + 实时同步)
*/
updateCatFood: (id: number, data: Partial<CatFood>) => {
const state = get();
const existingCatFood = state.entities[id];
if (!existingCatFood) {
logger.warn('猫粮不存在,跳过更新', { id });
return;
}
const updatedCatFood = { ...existingCatFood, ...data };
set({
entities: {
...state.entities,
[id]: updatedCatFood,
},
});
logger.debug('更新猫粮数据', { id, fields: Object.keys(data) });
},
/**
* 批量更新多个猫粮数据(用于实时同步)
*/
batchUpdateCatFoods: (updates: { id: number; data: Partial<CatFood> }[]) => {
const state = get();
const newEntities = { ...state.entities };
updates.forEach(({ id, data }) => {
Eif (newEntities[id]) {
newEntities[id] = { ...newEntities[id], ...data };
}
});
set({ entities: newEntities });
logger.debug('批量更新猫粮', { count: updates.length });
},
/**
* 批量添加猫粮
*/
addCatFoods: (catfoods: CatFood[], listType: ListType = 'all') => {
const state = get();
const newEntities = { ...state.entities };
const newIds: number[] = [];
const timestamp = Date.now();
catfoods.forEach((catfood) => {
newEntities[catfood.id] = catfood;
newIds.push(catfood.id);
state.cacheMetadata[catfood.id] = {
timestamp,
expiresIn: CACHE_CONFIG.DEFAULT_EXPIRE,
};
});
const updatedList = [...state.lists[listType], ...newIds];
set({
entities: newEntities,
lists: {
...state.lists,
[listType]: Array.from(new Set(updatedList)),
},
cacheMetadata: { ...state.cacheMetadata },
});
logger.debug('批量添加猫粮', { count: catfoods.length, listType });
},
// ==================== 缓存管理 ====================
/**
* 检查缓存是否有效
*/
isCacheValid: (id: number) => {
const state = get();
const metadata = state.cacheMetadata[id];
if (!metadata) return false;
const now = Date.now();
const isValid = now - metadata.timestamp < metadata.expiresIn;
return isValid;
},
/**
* 清除过期缓存
*/
clearExpiredCache: () => {
const state = get();
const now = Date.now();
const validIds: number[] = [];
const newEntities: Record<number, CatFood> = {};
const newMetadata: Record<number, CacheMetadata> = {};
// 遍历所有entity,保留有效的
Object.entries(state.entities).forEach(([idStr, catfood]) => {
const id = Number(idStr);
const metadata = state.cacheMetadata[id];
if (metadata && now - metadata.timestamp < metadata.expiresIn) {
validIds.push(id);
newEntities[id] = catfood;
newMetadata[id] = metadata;
}
});
// 更新列表(移除无效ID)
const filterList = (list: number[]) => list.filter((id) => validIds.includes(id));
set({
entities: newEntities,
lists: {
all: filterList(state.lists.all),
search: filterList(state.lists.search),
favorites: filterList(state.lists.favorites),
},
cacheMetadata: newMetadata,
});
const removedCount = Object.keys(state.entities).length - validIds.length;
logger.info('清除过期缓存', { removedCount });
},
/**
* 清除所有缓存
*/
clearAllCache: () => {
set({
entities: {},
lists: {
all: [],
search: [],
favorites: [],
},
pagination: {
all: { ...INITIAL_PAGINATION },
search: { ...INITIAL_PAGINATION },
favorites: { ...INITIAL_PAGINATION },
},
cacheMetadata: {},
error: null,
});
logger.info('清除所有缓存');
},
// ==================== 工具方法 ====================
/**
* 根据ID获取猫粮
*/
getCatFoodById: (id: number) => {
return get().entities[id];
},
/**
* 获取指定列表的猫粮数组
*/
getCatFoodsByList: (listType: ListType = 'all') => {
const state = get();
const ids = state.lists[listType];
return ids.map((id) => state.entities[id]).filter(Boolean);
},
/**
* 设置加载状态
*/
setLoading: (loading: boolean) => {
set({ isLoading: loading });
},
/**
* 设置错误信息
*/
setError: (error: string | null) => {
set({ error });
},
/**
* 设置水化状态
*/
setHasHydrated: (hasHydrated: boolean) => {
set({ _hasHydrated: hasHydrated });
},
/**
* 重置状态(用于登出等场景)
*/
reset: () => {
set({
entities: {},
lists: {
all: [],
search: [],
favorites: [],
},
pagination: {
all: { ...INITIAL_PAGINATION },
search: { ...INITIAL_PAGINATION },
favorites: { ...INITIAL_PAGINATION },
},
cacheMetadata: {},
isLoading: false,
isRefreshing: false,
isLoadingMore: false,
error: null,
});
logger.info('重置猫粮Store');
},
}),
{
name: 'catFoodStorage',
storage: createJSONStorage(() => AsyncStorage),
// 持久化策略:只保存核心数据
partialize: (state) => ({
entities: state.entities,
lists: state.lists,
cacheMetadata: state.cacheMetadata,
}),
// 水化完成后的回调
onRehydrateStorage: () => (state) => {
Eif (state) {
logger.info('猫粮状态恢复完成', {
entityCount: Object.keys(state.entities).length,
allListCount: state.lists.all.length,
});
// 清除过期缓存
state.clearExpiredCache();
state.setHasHydrated(true);
}
},
}
)
);
// ==================== 便捷 Hooks ====================
/**
* 获取全部猫粮列表
* 使用 ID 字符串作为稳定的依赖,并监听 entities 变化以支持实时更新
*/
export const useAllCatFoods = () => {
// 订阅 IDs 数组
const allIds = useCatFoodStore((state) => state.lists.all);
const isLoading = useCatFoodStore((state) => state.isLoading);
const hasMore = useCatFoodStore((state) => state.pagination.all.hasMore);
// 订阅 entities 对象,当任何猫粮数据变化时触发更新
const entities = useCatFoodStore((state) => state.entities);
// 使用 ID 字符串和 entities 的引用作为依赖
const idsKey = allIds.join(',');
const catfoods = useMemo(() => {
return allIds.map((id) => entities[id]).filter(Boolean);
}, [allIds, entities]);
return { catfoods, isLoading, hasMore };
};
/**
* 根据ID获取猫粮
*/
export const useCatFood = (id: number) => {
return useCatFoodStore((state) => state.entities[id]);
};
/**
* 获取搜索结果
* 使用 ID 字符串作为稳定的依赖
*/
export const useSearchResults = () => {
// 订阅 IDs 数组
const searchIds = useCatFoodStore((state) => state.lists.search);
const isLoading = useCatFoodStore((state) => state.isLoading);
const hasMore = useCatFoodStore((state) => state.pagination.search.hasMore);
// 使用 ID 字符串作为稳定依赖,并通过 useCatFoodStore 获取实际数据
const idsKey = searchIds.join(',');
const results = useMemo(() => {
const state = useCatFoodStore.getState();
return searchIds.map((id) => state.entities[id]).filter(Boolean);
}, [idsKey]);
return { results, isLoading, hasMore };
};
|