Files
doodle-mini/miniprogram/utils/favorites.ts
T
2026-05-20 10:18:25 +08:00

136 lines
3.5 KiB
TypeScript

import { getUser } from './auth';
export interface FavoriteRecord {
_id: string;
userId: string;
worksheetId: string;
createdAt: string;
worksheet?: {
_id: string;
title: string;
subtitle: string;
category: string;
subcategory: string;
ageMin: number;
ageMax: number;
difficulty: number;
previewImg: string;
tags: string[];
} | null;
}
/**
* 添加收藏
*/
export async function addFavorite(worksheetId: string): Promise<boolean> {
try {
await getUser(); // 确保已登录
const res = await wx.cloud.callFunction({
name: 'userFavorites',
data: { action: 'add', worksheetId },
});
const result = (res?.result as any) || {};
return result.code === 0;
} catch (e) {
console.error('addFavorite failed', e);
return false;
}
}
/**
* 取消收藏
*/
export async function removeFavorite(worksheetId: string): Promise<boolean> {
try {
await getUser();
const res = await wx.cloud.callFunction({
name: 'userFavorites',
data: { action: 'remove', worksheetId },
});
const result = (res?.result as any) || {};
return result.code === 0;
} catch (e) {
console.error('removeFavorite failed', e);
return false;
}
}
/**
* 获取收藏列表
*/
export async function getFavoriteList(
page = 1,
pageSize = 20,
): Promise<FavoriteRecord[]> {
try {
await getUser();
const res = await wx.cloud.callFunction({
name: 'userFavorites',
data: { action: 'list', page, pageSize },
});
const result = (res?.result as any) || {};
return result.code === 0 ? result.data || [] : [];
} catch (e) {
console.error('getFavoriteList failed', e);
return [];
}
}
/**
* 获取当前用户收藏总数
*/
export async function getFavoriteCount(): Promise<number> {
try {
await getUser();
const res = await wx.cloud.callFunction({
name: 'userFavorites',
data: { action: 'count' },
});
const result = (res?.result as any) || {};
return result.code === 0 ? Number(result.data?.count || 0) : 0;
} catch (e) {
console.error('getFavoriteCount failed', e);
return 0;
}
}
/**
* 检查是否已收藏
*/
export async function checkFavorited(worksheetId: string): Promise<boolean> {
try {
await getUser();
const res = await wx.cloud.callFunction({
name: 'userFavorites',
data: { action: 'check', worksheetId },
});
const result = (res?.result as any) || {};
return result.code === 0 && result.data?.favorited;
} catch (e) {
console.error('checkFavorited failed', e);
return false;
}
}
/**
* 批量检查是否已收藏,返回 { worksheetId: true } 的 map
*/
export async function batchCheckFavorited(
worksheetIds: string[],
): Promise<Record<string, boolean>> {
if (!worksheetIds.length) return {};
try {
await getUser();
const res = await wx.cloud.callFunction({
name: 'userFavorites',
data: { action: 'batchCheck', worksheetIds },
});
const result = (res?.result as any) || {};
return result.code === 0 ? result.data || {} : {};
} catch (e) {
console.error('batchCheckFavorited failed', e);
return {};
}
}