How can I implement a HotChocolate FieldResolver when the resolved value depends on another field?

How can I implement a HotChocolate FieldResolver when the resolved value depends on another field?


0

I have the following code designed to apply a list of errors to resolved items by fetching the full list of errors from another service which that caches them for performance reasons:

public class MyEntityExtensions : ObjectType<MyEntity>
{
    protected override void Configure(IObjectTypeDescriptor<MyEntity> descriptor)
    {
        descriptor
            .Field("errors")
            .Type(typeof(List<Error>))
            .Resolve(async context =>
            {
                var errorCache = context.Service<ErrorCache>();

                var entityId = ???;

                var errors = await errorCache.Get(entityId);

                return errors ;
            });
    }
}

How can I get the Id property of the current Entity to pass as the argument to the cache?

For a declarative approach, there doesn’t seem to be any way to enforce resolver order or declare dependencies between fields. For a runtime approach, there doesn’t seem to be any property on the MiddlewareContext that holds any information related to other fields on the same object. The only way to reference a resolved item seems to be .Parent<> but this isn’t a hierarchy.

I’ve tried several different approaches to setting up this middleware and several ways of trying to manipulate order of operations via the .Use() method but no luck.

Is this possible with the current approach? If not, is there another approach that doesn’t require stitching the errors as a completely separate data source?

Share

1 Answer
1

Reset to default


0

You can use context.Parent like this:

public class MyEntityExtensions : ObjectType<MyEntity>
{
    protected override void Configure(IObjectTypeDescriptor<MyEntity> descriptor)
    {
        descriptor
            .Field("errors")
            .Type(typeof(List<Error>))
            .Resolve(async context =>
            {
                var errorCache = context.Service<ErrorCache>();

                var entityId = context.Parent<MyEntity>().Id; // Here

                var errors = await errorCache.Get(entityId);

                return errors ;
            });
    }
}

Share



Leave a Reply

Your email address will not be published. Required fields are marked *