0

Apologies if this has been asked before, but I wanted to ask about how I can re-use certain logic between fields in a graphql-dotnet type class ?

For e.g.

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;
                ...

                .....
            });

And this same logic needs to be used all over the place,

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

What wold be the right way to calculate valueSharedBetweenSomeAndAnotherField like a variable just once outside the field resolvers, so I can just calculate it once and re-use it directly inside the type resolvers for somefield and anotherfield ?

Thank you!

user1427026
  • 861
  • 2
  • 16
  • 32

1 Answers1

0

You could move the logic which gets that information into another method and call it from both places,

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;
}

Now you just call this from the other places.