NotificationService.cs 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. using Application.Abstractions.Data;
  2. using Application.Abstractions.Hub;
  3. using Application.Abstractions.Notification;
  4. using Domain.Entities.Notifications.ValueObject;
  5. using Infrastructure.Hubs;
  6. using Microsoft.AspNetCore.SignalR;
  7. using Microsoft.EntityFrameworkCore;
  8. namespace Infrastructure.Notification;
  9. internal sealed class NotificationService(
  10. IAppDbContext db,
  11. IHubContext<AppHub, IAppHubClient>? appHub = null
  12. ) : INotificationService
  13. {
  14. public async Task SendAsync(
  15. int memberID, NotificationType type, string title, string message,
  16. string? actionUrl, string? relatedType, int? relatedID, string? imageUrl,
  17. CancellationToken ct)
  18. {
  19. var notification = Domain.Entities.Notifications.Notification.Create(
  20. memberID, type, title, message, actionUrl, relatedType, relatedID, imageUrl
  21. );
  22. db.Notification.Add(notification);
  23. await db.SaveChangesAsync(ct);
  24. // SignalR Push (Hub가 등록된 경우에만)
  25. if (appHub is not null)
  26. {
  27. await appHub.Clients.Group($"member:{memberID}").ReceiveNotification(new
  28. {
  29. notification.ID, notification.Type, notification.Title,
  30. notification.Message, notification.ActionUrl, notification.ImageUrl,
  31. notification.CreatedAt
  32. });
  33. var unreadNotif = await db.Notification.CountAsync(n => n.MemberID == memberID && !n.IsRead, ct);
  34. var unreadNote = await db.Note.CountAsync(n => n.ReceiverMemberID == memberID && !n.IsDeletedByReceiver && !n.IsRead, ct);
  35. await appHub.Clients.Group($"member:{memberID}").ReceiveUnreadCounts(unreadNotif, unreadNote);
  36. }
  37. }
  38. public async Task SendToManyAsync(
  39. IEnumerable<int> memberIDs, NotificationType type, string title, string message,
  40. string? actionUrl, string? relatedType, int? relatedID, string? imageUrl,
  41. CancellationToken ct)
  42. {
  43. foreach (var memberID in memberIDs)
  44. {
  45. await SendAsync(memberID, type, title, message, actionUrl, relatedType, relatedID, imageUrl, ct);
  46. }
  47. }
  48. }