comment.service.ts 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. import { PrismaService } from '@/prisma/prisma.service'
  2. import { Injectable } from '@nestjs/common'
  3. @Injectable()
  4. export class CommentService {
  5. constructor(private readonly prisma: PrismaService) {}
  6. // 发表评论
  7. async createComment(content: string, articleId: number, userId: number) {
  8. const data = await this.prisma.comment.create({
  9. data: {
  10. authorId: userId,
  11. content: content,
  12. postId: articleId,
  13. },
  14. })
  15. return { cod: 200, msg: '发表评论成功', data }
  16. }
  17. // 删除评论
  18. async deleteComment(userId: number, Commentid: number) {
  19. const data = await this.prisma.comment.findFirst({
  20. where: {
  21. id: Commentid,
  22. },
  23. })
  24. if (!data) {
  25. return { cod: 400, msg: '评论不存在' }
  26. }
  27. if (data.authorId !== userId) {
  28. return { cod: 400, msg: '无权删除评论' }
  29. }
  30. await this.prisma.comment.delete({
  31. where: {
  32. id: Commentid,
  33. },
  34. })
  35. return { cod: 200, msg: '删除评论成功', data }
  36. }
  37. async getComment(postId: number, page: number = 1, limit: number = 10) {
  38. const data = await this.prisma.comment.findMany({
  39. skip: (page - 1) * limit,
  40. take: limit,
  41. // 时间最新排序
  42. orderBy: {
  43. createdAt: 'desc',
  44. },
  45. where: {
  46. postId: postId,
  47. },
  48. })
  49. data.map((item) => {
  50. delete item.postId
  51. delete item.createdAt
  52. return item
  53. })
  54. //总页数
  55. const total = await this.prisma.comment.count({
  56. where: {
  57. postId: postId,
  58. },
  59. })
  60. //总条数
  61. const totalPage = Math.ceil(total / limit)
  62. return { cod: 200, msg: '获取评论成功', data, total, totalPage }
  63. }
  64. //修改评论
  65. async updateComment(userId: number, Commentid: number, content: string) {
  66. const data = await this.prisma.comment.findFirst({
  67. where: {
  68. id: Commentid,
  69. },
  70. })
  71. if (!data) {
  72. return { cod: 400, msg: '评论不存在' }
  73. }
  74. if (data.authorId !== userId) {
  75. return { cod: 400, msg: '无权修改评论' }
  76. }
  77. await this.prisma.comment.update({
  78. where: {
  79. id: Commentid,
  80. },
  81. data: {
  82. content: content,
  83. },
  84. })
  85. return { cod: 200, msg: '修改评论成功', data }
  86. }
  87. }