返回 presentation-ai
theme-favorite-actions.ts
根目录 / src / app / _actions / presentation / theme-favorite-actions.ts
1 "use server";
2
3 import { auth } from "@/server/auth";
4 import { db } from "@/server/db";
5
6 // Toggle favorite status for a theme
7 export async function toggleFavoriteTheme(themeId: string) {
8 try {
9 const session = await auth();
10 if (!session?.user) {
11 return {
12 success: false,
13 message: "You must be signed in to favorite themes",
14 isFavorite: false,
15 };
16 }
17
18 // Check if theme exists
19 const theme = await db.presentationTheme.findUnique({
20 where: { id: themeId },
21 });
22
23 if (!theme) {
24 return { success: false, message: "Theme not found", isFavorite: false };
25 }
26
27 // Check if already favorited
28 const existingFavorite = await db.favoritePresentationTheme.findUnique({
29 where: {
30 userId_themeId: {
31 userId: session.user.id,
32 themeId,
33 },
34 },
35 });
36
37 if (existingFavorite) {
38 // Remove favorite
39 await db.favoritePresentationTheme.delete({
40 where: {
41 userId_themeId: {
42 userId: session.user.id,
43 themeId,
44 },
45 },
46 });
47 return {
48 success: true,
49 isFavorite: false,
50 message: "Theme removed from favorites",
51 };
52 } else {
53 // Add favorite
54 await db.favoritePresentationTheme.create({
55 data: {
56 userId: session.user.id,
57 themeId,
58 },
59 });
60 return {
61 success: true,
62 isFavorite: true,
63 message: "Theme added to favorites",
64 };
65 }
66 } catch (error) {
67 console.error("Failed to toggle favorite:", error);
68 return {
69 success: false,
70 message: "Something went wrong. Please try again later.",
71 isFavorite: false,
72 };
73 }
74 }
75
76 // Get favorite themes for the current user, including like counts and user liked flag
77 export async function getUserFavoriteThemes() {
78 try {
79 const session = await auth();
80 if (!session?.user) {
81 return {
82 success: false,
83 message: "You must be signed in to view favorite themes",
84 themes: [],
85 };
86 }
87
88 const favorites = await db.favoritePresentationTheme.findMany({
89 where: {
90 userId: session.user.id,
91 },
92 include: {
93 theme: {
94 include: {
95 user: {
96 select: {
97 name: true,
98 },
99 },
100 _count: {
101 select: {
102 presentationThemeLikes: true,
103 },
104 },
105 presentationThemeLikes: {
106 where: {
107 userId: session.user.id,
108 },
109 select: {
110 id: true,
111 },
112 },
113 },
114 },
115 },
116 orderBy: {
117 createdAt: "desc",
118 },
119 });
120
121 const themes = favorites.map((fav) => ({
122 ...fav.theme,
123 likeCount: fav.theme._count.presentationThemeLikes,
124 isLiked: !!fav.theme.presentationThemeLikes?.length,
125 isFavorite: true,
126 }));
127
128 return {
129 success: true,
130 themes,
131 };
132 } catch (error) {
133 console.error("Failed to fetch favorite themes:", error);
134 return {
135 success: false,
136 message: "Unable to load favorite themes. Please try again later.",
137 themes: [],
138 };
139 }
140 }
141
141 lines TYPESCRIPT