HotChocolate: How to access "connection_init" payload

Viewed 385

We are sending additional payload during connection_init (connectionParams in https://github.com/apollographql/subscriptions-transport-ws for Apollo).

I was unable to find any information on how to extract such information nor any kind of information on any message middlewares/handlers in the official sources.

Concurrent solution graphql-dotnet allows me to implement IOperationMessageListener like this

public class SusbcriptionInitListener: IOperationMessageListener
{
    public Task BeforeHandleAsync(MessageHandlingContext context) => Task.CompletedTask;
    
    // This method will be triggered with every incoming message
    public async Task HandleAsync(MessageHandlingContext context)
    {
        var message = context.Message;
        
        // I can then filter for specific message type and do something with the raw playload
        if (message.Type == MessageType.GQL_CONNECTION_INIT)
        {
            string myInformation = message.Payload.GetValue("MyInfomration").ToString();
            
            DoSomethingWithMyInformation(myInformation);
        }
    }

    public Task AfterHandleAsync(MessageHandlingContext context) => Task.CompletedTask;
}

Does HC provide anything similar?

1 Answers

What you are looking for is the ISocketSessionInterceptor

services
   AddGraphQLServer()
   ... Your Config
   .AddSocketSessionInterceptor<AuthenticationSocketInterceptor>();
public interface ISocketSessionInterceptor
    {
        ValueTask<ConnectionStatus> OnConnectAsync(
            ISocketConnection connection,
            InitializeConnectionMessage message,
            CancellationToken cancellationToken);

        ValueTask OnRequestAsync(
            ISocketConnection connection,
            IQueryRequestBuilder requestBuilder,
            CancellationToken cancellationToken);

        ValueTask OnCloseAsync(
            ISocketConnection connection,
            CancellationToken cancellationToken);
    }

You can access the connection request payload by overriding OnConnectAsync.

The InitializeConnectionMessage contains a Payload property that holds the payload

Related