Serverless signalR: Adding a user to a group and sending a message to the group simultaneously in upstream

95 Views Asked by At

I wrote the following code with the hope of adding a user to a group and sending a message to the user's group simultaneously. I can see the connections established per the signalR's blade on my Azure's Portal but I cannot conclude whether or not the user has become a member of the group after returning this function.

    [Function("OnConnected")]
    [SignalROutput(HubName = "myhub")]
    public async Task<object[]> OnConnectedAsync([SignalRTrigger("myhub", "connections", "connected")] SignalRInvocationContext invocationContext)
    {
        var username = "userA";
        var groupName = "groupA";
        return
        [
            new SignalRGroupAction(SignalRGroupActionType.Add)
            {
                GroupName = groupName,
                UserId = username
            },
            new SignalRMessageAction("NewUserConnected")
            {
                GroupName = groupName,
                Arguments = [userName]
            }
        ];
    }

Does the function's implementation above exhibit a right approach to add a user to the group and send a message to the group at the same time?

Note: Before writing this code, I tried to add the user to the group by the following line of code while having the function above report SignalRMessageAction object but it threw an exception:

await UserGroups.AddToGroupAsync(userName, groupName);

Apparently signalR's SDK does not like the line above in the context of upstreams.

1

There are 1 best solutions below

2
Sampath On

The code below adds a user to a group and sends a message to the group. The Azure Function SendMessage is designed to handle POST requests and send messages to a SignalR group named "myGroup" using output binding.

  • It reads the request body to extract userId and message.

  • It adds the userId to the SignalR group "myGroup".

  • It sends the message to the SignalR group "myGroup".

  • Azure Functions SignalR Service output binding reference.

Adds a user to a group and sends a message to the group:

 [FunctionName("SendMessage")]
    public static async Task<IActionResult> SendMessage(
        [HttpTrigger(AuthorizationLevel.Anonymous, "post")] HttpRequest req,
        [SignalR(HubName = "sampathravi90ravi")] IAsyncCollector<SignalRGroupAction> signalRGroupActions,
        [SignalR(HubName = "sampathravi90ravi")] IAsyncCollector<SignalRMessage> signalRMessages,
        ILogger log)
    {
        log.LogInformation("C# HTTP trigger function processed a request.");

        string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
        dynamic data = JsonConvert.DeserializeObject(requestBody);

        string userId = data?.userId;
        string message = data?.message;

        if (userId != null && message != null)
        {
            // Add user to group
            await signalRGroupActions.AddAsync(
                new SignalRGroupAction
                {
                    UserId = userId,
                    GroupName = "myGroup",
                    Action = GroupAction.Add
                });

            // Send message to group
            await signalRMessages.AddAsync(
                new SignalRMessage
                {
                    GroupName = "myGroup",
                    Target = "newMessage",
                    Arguments = new[] { message }
                });

            log.LogInformation($"Sent message: {message} to group myGroup for user {userId}");

            return new OkResult();
        }
        else
        {
            log.LogError("Either userId or message not found in the request body.");
            return new BadRequestObjectResult("Please pass userId and message in the request body.");
        }
    }

{

"userId": "userId1",

"message": "Hello, world!"

}

Output: enter image description here enter image description here