如何解决HotChocolate 将 UseFiltering 应用于字段以及 QueryType 中的解析器 更新以将字段 "filter" 声明为 QueryType 类中的方法
我在查询类型中使用带有 UseFiltering() 方法的解析器时遇到问题。
目前,我正在对查询类型的所有字段使用解析器。我不知道这是否是最佳实践。我将说明暂存代码。
public class QueryType {
// nothing here just a empty class
}
public class QueryTypeWithFieldResolvers : ObjectType<QueryType>
{
protected override void Configure(IObjectTypeDescriptor<QueryType> descriptor)
{
base.Configure(descriptor);
descriptor.Field(nameof(GenericResolvers<User>.Get))
.Name("get")
.Type<ListType<ObjectType<User>>>()
.ResolveWith<GenericResolvers<User>>(r => r.Get(default!));
descriptor.Field(nameof(GenericResolvers<User>.GetById))
.Name("getById")
.Argument("id",argsDescriptor => argsDescriptor.Type<StringType>()
.Type<ObjectType<User>>()
.ResolveWith<GenericResolvers<User>>(r => r.GetById(default!,default!));
}
}
以上一切仍然正常工作。直到我想添加 Filtering 并使用这种方法将 Resolver 用于查询类型中名为 "filter" 的新字段。
似乎过滤中间件没有按预期工作,它返回数据库中的所有数据。
public class QueryTypeWithFieldResolvers : ObjectType<QueryType>
{
protected override void Configure(IObjectTypeDescriptor<QueryType> descriptor)
{
// omitted
...
descriptor.Field(nameof(GenericResolvers<User>.Filter))
.Name("filter")
.Type<ListType<ObjectType<User>>>>()
.ResolveWith<GenericResolvers<User>>(r => r.Filter(default!))
.UseFiltering<UserFilterInputType>();
}
}
更新以将字段 "filter" 声明为 QueryType 类中的方法
通过这种方法,它可以按照 Hotchocolate Filtering
的说明工作public class QueryType {
public IQueryable<User> Filter([Service] IGenericRepository<User> repo)
{
return repo.Query();
}
}
public class QueryTypeWithFieldResolvers : ObjectType<QueryType>
{
protected override void Configure(IObjectTypeDescriptor<QueryType> descriptor)
{
// omitted
...
// updated to use field expression directly
descriptor.Field(f => f.Filter(default!))
.Type<ListType<ObjectType<User>>>()
.UseFiltering();
}
}
据我所知,它们都是 HotChocolate 的有效代码优先方法,但我不知道上述两种方法之间有什么区别。所以请帮我解释一下为什么伙计们?提前致谢。
解决方法
public class UserFilterInputType : FilterInputType<UserInput>
{
protected override void Configure(IFilterInputTypeDescriptor<UserInput> descriptor)
{
}
}
public class UserInputType : InputObjectType<UserInput>
{
protected override void Configure(IInputObjectTypeDescriptor<UserInput> descriptor)
{
descriptor.Field(t => t.Id).Type<StringType>().Name("id");
descriptor.Field(t => t.Username).Type<StringType>().Name("userName");
}
public class UserInput
{
public string Id { get; set; }
public string Username { get; set; }
}
这是我的错误,因为使用了泛型 UseFiltering<T>()
。并且约束是FilterInputType<UserInput>
,它必须是FilterInputType<User>
。因为我们操作的是域类User而不是输入类
这就是为什么它会导致无法在过滤中间件中工作的问题。 我需要做的就是将 FilterInputType 的约束从 UserInput 更改为 User
public class UserFilterInputType : FilterInputType<User>
{
protected override void Configure(IFilterInputTypeDescriptor<User> descriptor)
{
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。