0

抱歉,如果以前有人问过这个问题,但我想问一下如何在 graphql-dotnet 类型类中的字段之间重用某些逻辑?

例如

public MyClassType()
{
Name = "MyClassType";
Field<SomeEncloserType>(
            name: "somefield",
resolve: context =>
            {
                var requestName = context.Path.First().ToString();
                var vibrancySettings = (VibrancySettings)context.Variables.ValueFor(requestName);
                var otherSettings = vibrancySettings.SomeOtherSettings;
                var valueSharedBetweenSomeAndAnotherField = otherSettings.SomeCalcProperty;
                ...

                .....
            });

到处都需要使用同样的逻辑,

Field<SomeEncloserType>(
            name: "anotherfield",
resolve: context =>
            {
                var requestName = context.Path.First().ToString();
                var vibrancySettings = (VibrancySettings)context.Variables.ValueFor(requestName);

什么是计算 valueSharedBetweenSomeAndAnotherField 的正确方法,就像在字段解析器之外的变量一样,所以我可以只计算一次并直接在 somefield 和 anotherfield 的类型解析器中重新使用它?

谢谢!

4

1 回答 1

0

您可以将获取该信息的逻辑移动到另一个方法中并从两个地方调用它,

public static TypeOfSomeOtherCalc GetSomeOtherCalc(IResolveContext context)
{
  var requestName = context.Path.First().ToString();
  var vibrancySettings = (VibrancySettings)context.Variables.ValueFor(requestName);
  var otherSettings = vibrancySettings.SomeOtherSettings;
  var valueSharedBetweenSomeAndAnotherField = otherSettings.SomeCalcProperty;
  return valueSharedBetweenSomeAndAnotherField;
}

现在你只需从其他地方调用它。

于 2021-08-25T14:36:35.950 回答