This feature request is a logical continuation of https://github.com/ChilliCream/hotchocolate/issues/1021.
Thanks to CollectFields helper I get a complete list of requested fields. And now I want to map this fields to database columns, and I think about where to store this mapping... The easiest option is to simply store the dictionary in resolvers:
public class ArticleType : ObjectType<Article>
{
protected override void Configure(IObjectTypeDescriptor<Article> descriptor)
{
<...>
descriptor.Field("authors")
.Type<NonNullType<ListType<AuthorType>>>()
.Resolver(ctx =>
{
var fields = ctx.CollectFields((AuthorType)ctx.Field.Type.NamedType());
var mapping = new Dictionary<string, string[]>() {
{ "id", new string[] { "id" } },
{ "fullName", new string[] { "surname", "name" } }
}
<data fetching stuff...>
});
<...>
}
}
But this option is ugly and non-declarative, since columns of a different type must be stored in the resolver of another type. It would be useful to store custom data in the field description like this:
public class AuthorType : ObjectType<Author>
{
protected override void Configure(IObjectTypeDescriptor<Author> descriptor)
{
descriptor.Field(t => t.Id)
.Type<NonNullType<IntType>>()
.Attribute("dependencies", new string[] { "id" });
descriptor.Field(t => t.FullName)
.Type<NonNullType<StringType>>()
.Attribute("dependencies", new string[] { "surname", "name" });
}
}
Thanks to this feature, CollectFields can return my custom attributes to me. Do you think this is a useful feature, or can it be implemented in another way?
This already exits, we call it ContextData. Every object, field etc has a ContextData dictionary that becomes immutable after the type is created.
I will send you some code on Monday.
@michaelstaib I have found some info about ContextData. As I understand it, I can set context data only via middleware in Startup? How to set data in declarative way with field definition?
@acelot sorry for the wait. No context data are everywhere. So any object field etc has custom context data ....
Accessing ContextData
query.ContextData
Setting context data.
descriptor.Extend().OnBeforeCreate(c => c.ContextData["foo"] = "jfkdjslf")
The context data as we thought about it was meant to support extensions ... so you get it through the extension point of each descriptor.
We could make this easier for the next version. But this is how you can do it today.
descriptor.Field(t => t.FullName)
.Type<NonNullType<StringType>>()
descriptor.Extend().OnBeforeCreate(c => c.ContextData["dependencies"] = new string[] { "surname", "name" });
var dips = (string[])obj.Fields["fullName"].ContextData["dependencies"]