favorites.service.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.getFavorites = getFavorites;
  4. exports.addFavorite = addFavorite;
  5. exports.removeFavorite = removeFavorite;
  6. exports.isFavorited = isFavorited;
  7. const client_1 = require("@prisma/client");
  8. const prisma = new client_1.PrismaClient();
  9. /**
  10. * 获取用户收藏列表(收藏的是书籍)
  11. */
  12. async function getFavorites(userId) {
  13. const userIdNum = parseInt(userId);
  14. const favorites = await prisma.favorite.findMany({
  15. where: { userId: userIdNum },
  16. include: {
  17. book: {
  18. select: {
  19. id: true,
  20. title: true,
  21. subtitle: true,
  22. description: true,
  23. coverUrl: true,
  24. createdAt: true,
  25. },
  26. },
  27. },
  28. orderBy: { createdAt: 'desc' },
  29. });
  30. return favorites;
  31. }
  32. /**
  33. * 添加收藏(收藏书籍)
  34. */
  35. async function addFavorite(userId, bookId) {
  36. const userIdNum = parseInt(userId);
  37. // 检查是否已存在
  38. const existing = await prisma.favorite.findUnique({
  39. where: {
  40. userId_bookId: {
  41. userId: userIdNum,
  42. bookId,
  43. },
  44. },
  45. });
  46. if (existing) {
  47. return existing;
  48. }
  49. return await prisma.favorite.create({
  50. data: {
  51. userId: userIdNum,
  52. bookId,
  53. },
  54. include: {
  55. book: {
  56. select: {
  57. id: true,
  58. title: true,
  59. subtitle: true,
  60. description: true,
  61. coverUrl: true,
  62. createdAt: true,
  63. },
  64. },
  65. },
  66. });
  67. }
  68. /**
  69. * 取消收藏
  70. */
  71. async function removeFavorite(userId, bookId) {
  72. const userIdNum = parseInt(userId);
  73. return await prisma.favorite.delete({
  74. where: {
  75. userId_bookId: {
  76. userId: userIdNum,
  77. bookId,
  78. },
  79. },
  80. });
  81. }
  82. /**
  83. * 检查是否已收藏
  84. */
  85. async function isFavorited(userId, bookId) {
  86. const userIdNum = parseInt(userId);
  87. const favorite = await prisma.favorite.findUnique({
  88. where: {
  89. userId_bookId: {
  90. userId: userIdNum,
  91. bookId,
  92. },
  93. },
  94. });
  95. return !!favorite;
  96. }