【问题标题】:Is there a way to resolve a GraphQl type by referencing another type?有没有办法通过引用另一种类型来解析 GraphQl 类型?
【发布时间】:2020-08-17 02:44:00
【问题描述】:

我正在使用 Graphql .Net 库来构建 GraphQl API。 以下是我们目前拥有的域示例,其中,该区域有一个采样点标识符列表:

public class AreaRoot {
   public String Id { get; set; }
   public List<String > SamplingPointIds { get; set; }
}

public class SamplingPointRoot {
   public String Id { get; set; }
   public String Description { get; set; }
}

类型定义如下:

public class AreaType : ObjectGraphType<AreaRoot>
{
    public AreaType()
    {
        Name = "Area";
        Field(x => x.Id, type: typeof(IdGraphType));
        Field(x => x.SamplingPointIds, type: typeof(ListGraphType<StringGraphType>));
    }
}

public class SamplingPointType : ObjectGraphType<SamplingPointRoot>
{
    public SamplingPointType()
    {
        Name = "SamplingPoint";
        Field(x => x.Id, type: typeof(IdGraphType));
        Field(x => x.description, type: typeof(StringGraphType));
    }
}

有什么方法可以在不更改域类的情况下从采样点检索所有内容?在会议GraphQL vs Traditional Rest API 中有一个示例,在 25:41 分钟内,但是这个示例是用 java 编写的,我们无法使用 graphQl .net 制作相同的示例。

下一个示例说明了我们想要进行的查询类型:

query GetAreas(){
    areas(){
        Id
        samplingPoints{
           Id
           description
        }
    }
}

所以问题是:有没有办法像上面的视频中那样,当我们传递采样点并解决它,检索该区域的采样点(在某些查询中)?

【问题讨论】:

    标签: c# .net-core graphql


    【解决方案1】:

    问题已在 github 上解决。对于那些尝试做同样的事情的人来说,实际上真的很容易,我们只需要像这样在 AreaType 中有解析器:

    public class AreaType : ObjectGraphType<AreaRoot>
    {
        public AreaType(IRepository repository)
        {
            Name = "Area";
            Field(x => x.Id, type: typeof(IdGraphType));
            Field<ListGraphType<SamplingPointType>>("areaSamplingPoints",
               resolve: context =>
            {
               return repository.GetAllByAreaId(context.Source?.Id);
            });
        }
    }
    

    注意用于访问区域 ID 的 context.Source?.Id...

    而且,如果您尝试访问顶级上下文的参数,那么您不能,如 here 所述,但是,您可以访问传递给查询的变量,而不是最好的,但不是最糟糕的,所以使用:context.Variables.ValueFor("variableName")

    【讨论】:

      猜你喜欢
      • 2021-03-28
      • 2019-09-07
      • 1970-01-01
      • 2021-03-11
      • 2022-06-21
      • 1970-01-01
      • 2011-11-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多