Read real-time data from mysql with Signal R

Viewed 70

I want to know if there is a way to read data changes on MySQL with signal R. I saw that you can do this on SQL with SQL dependency. My objective is to do this to display notifications on ASP .Net Core. This is what I have:

Hub

 public class NotificationsHub : Hub
{
    private readonly INotificationsUserService _notificationsUserService;
    private readonly IMapper _mapper;
    public NotificationsHub(INotificationsUserService notificationsUserService, IMapper mapper)
    {
        _notificationsUserService= notificationsUserService;
        _mapper = mapper;
    }
    public async Task GetNotifications(int userId)
    {
        var notifications = await _notificationsUserService.GetAllNotificationUsers();
        notifications = notifications .Where(n => n.IdUser == userId);
        var userNotifications = new List<Notifications>();
        foreach (var item in notifications )
        {
            userNotifications.Add(item.IdNotificationsNavigation);
        }
        var notificationResource = _mapper.Map<IEnumerable<Notifications>, IEnumerable<NotificationsResource>>(userNotifications);
        await Clients.All.SendAsync("usersNotifications", notificationResource);
    }
}

Js

$(() => {
let connection = new signalR.HubConnectionBuilder().withUrl("/notificationsHub").build();
let userId = $('#userId').html();

setInterval(function () {
    connection.start().then(() => {
        connection.invoke("GetNotificationes", parseInt(userId)).catch(function (err) {
            return console.error(err.toString());
        });
    });
}, 5000);

var notificaciones = 
connection.on("usersNotifications", function (notifications) {
    $.ajax({
        type: "POST",
        url: "/Home/RefreshNavComponent",
        data: {
            "notifications": notifications
        },
        success: function (data) {
            $('#header').html(data);
            connection.stop();
        },
        error: function (req, status, error) {
            alert(req + " " + status + " " + error);
            console.log(req);
            console.log(status);
        }
    });
});

Home Controller

[HttpPost]
    public IActionResult RefreshNavComponent(IEnumerable<NotificationsResource> notifications)
    {
        if (notifications != null)
        {
            return ViewComponent("NavMenu", notifications);
        }
        return Ok();
    }

As you can see, currently im updating every 5 seconds my Nav where the notifications icon is. But I dont want it to update the full Nav. And I think calling a timer defeats the purpose of Signal R. Let me know if you have any suggestions.

1 Answers

Not seeing it in your code, so assuming that you have a method that updates the notifications table/record in the database. You can update your clients by using a Client.All or Clients.User(user) or Clients.Group(groupName) in the same method but after the update.

If you do this from a controller and not the Hub, you will want to check out how to send from outside the hub.

Related