Lucas Phillip
Lucas Phillip

Reputation: 185

How to access HotChocolate (GraphQL) requested query using IoC

I am trying to improve the sql query performance with hotchocolate. For that, I wanted to access the queryrequest generated by hotchololate in another layer of my app. The only way I could find to do this was to intercept the request, store the information I need withing HttpContext items, and then, inject the IHttpContextAccessor wherever I needed it.

services.AddQueryRequestInterceptor(GraphQLRequestInterceptor);
...
private Task GraphQLRequestInterceptor(HttpContext context, IQueryRequestBuilder requestBuilder, CancellationToken cancellationToken)
{
    IReadOnlyQueryRequest request = requestBuilder.Create();
    context.Items.Add("graph", request);
}

And then recover it by injecting IHttpContextAccessor

public ClientesQueries(Microsoft.AspNetCore.Http.IHttpContextAccessor contextAccessor)
{
   var queryRequest = contextAccessor.HttpContext.Items["graph"] as IReadOnlyQueryRequest;
}

With that code, I can create an expression to query my database for only the data that was requested by the client.

Is there a better way to achive this?

Upvotes: 0

Views: 5163

Answers (1)

MaxThom
MaxThom

Reputation: 1401

i'm not exactly sure my answer is what you have a requested, but this is how I access my httpContext in my graphql requests.

Simply adding : [Service]IHttpContextAccessor httpContext as methods first arguments.

Complete example in my code :

public async Task<IEnumerable<Tenant>> GetTenants([Service]IHttpContextAccessor httpContext)
{
    var tenantId = await httpContext.HttpContext.GetUserTenantId();
    return await _metadataRepo.Tenants.Get(x => x.TenantId == tenantId);
}

You dont need to create an interceptor. HttpContext is already in the DI of HotChocolate.

Upvotes: 5

Related Questions