0
votes

I have implemented negotiate endpoint and send method and connected from signalR JS client. I am getting the connection and able to broadcast message to all connected clients. As per our requirement, I have to send the message to a few clients. From the documentation, I believe we can send messages to a group. I have written an azure function for Adding and removing a user to a group.

 [FunctionName("AddToGroup")]
        public static Task AddToGroup(
            [HttpTrigger(AuthorizationLevel.Function, "get")] HttpRequest req,
            ILogger log,
            [SignalR(HubName = NotificationConstants.Hub)]IAsyncCollector<SignalRGroupAction> signalRGroupActions)
        {
            string userId = req.Query[NotificationConstants.QueryStringUserId];
            string companyId = req.Query[NotificationConstants.QueryStringCompanyId];
            return signalRGroupActions.AddAsync(
                 new SignalRGroupAction
                 {
                     UserId = userId,
                     GroupName = string.Format(CultureInfo.CurrentCulture,
                                NotificationConstants.Group,
                                companyId),
                     Action = GroupAction.Add
                 });
        }

    [FunctionName("RemoveFromGroup")]
    public static Task removeFromGroup(
       [HttpTrigger(AuthorizationLevel.Function, "get")] HttpRequest req,
       ILogger log,
       [SignalR(HubName = NotificationConstants.Hub)]IAsyncCollector<SignalRGroupAction> signalRGroupActions)
    {
        string userId = req.Query[NotificationConstants.QueryStringUserId];
        string companyId = req.Query[NotificationConstants.QueryStringCompanyId];
        return signalRGroupActions.AddAsync(
             new SignalRGroupAction
             {
                 UserId = userId,
                 GroupName = string.Format(CultureInfo.CurrentCulture,
                            NotificationConstants.Group,
                            companyId),
                 Action = GroupAction.Remove
             });
    }

How I can call this from JS Client? My sample client code as below. Please suggest

function GetConnectionInfo() {
    return axios.get('http://localhost:7071/api/ConnectionInfo?UserId=1_2347')
        .then(function (response) {
            return response.data;
        }).catch(console.error);
}

function StartConnection(connection) {
    console.log('connecting...');
    connection.start()
        .then(function () {
            console.log('connected!');
            connection.invoke('getConnectionId')
                .then(function (connectionId) {
                    console.log(connectionId);
                    // Send the connectionId to controller
                });

        })
        .catch(function (err) {
            console.error(err);
            setTimeout(function () { StartConnection(connection); }, 2000);
        });
}

GetConnectionInfo().then(function (info) {
    let accessToken = info.accessToken;
    const options = {
        accessTokenFactory: function () {
            if (accessToken) {
                const _accessToken = accessToken;
                accessToken = null;
                return _accessToken;
            } else {
                return GetConnectionInfo().then(function (info) {
                    return info.accessToken;
                });
            }

        }
    };

    const connection = new signalR.HubConnectionBuilder()
        .withUrl(info.url, options)
        .build();
    StartConnection(connection);

    connection.on('DocumentStatusUpdated', ProcessDocumentData);

    connection.onclose(function () {
        console.log('disconnected');
        setTimeout(function () { StartConnection(connection); }, 5000);
    });
}).catch(console.error);

Can someone please guide me.

Thanks

1

1 Answers

0
votes

Based on the code you've shared, you would need the userId and companyId of the users you want add into your group and simple make axios.get() calls accordingly.

For sending the message to the specific group, you would need one more function. The doc has sample code for the same. Here is the same for reference

[FunctionName("SendMessage")]
public static Task SendMessage(
    [HttpTrigger(AuthorizationLevel.Anonymous, "post")]object message,
    [SignalR(HubName = "chat")]IAsyncCollector<SignalRMessage> signalRMessages)
{
    return signalRMessages.AddAsync(
        new SignalRMessage
        {
            // the message will be sent to the group with this name
            GroupName = "myGroup",
            Target = "newMessage",
            Arguments = new [] { message }
        });
}

And you would make an axios.post() call to this endpoint to send a message to the group created earlier.