A note on using async computed fields with Optimizely Graph
Computed fields can be async, but do they work smoothly with the Graph C# SDK?
When getting computed values into the Graph index I've been using async methods such as this one:
async Task<string> SearchApplicationName(
IServiceProvider sp = null,
CancellationToken cancellationToken = default)
{
if (this is PageData currentPage)
{
var applicationResolver = sp!.GetService<IApplicationResolver>();
var application = await applicationResolver.GetByContentAsync(currentPage.ContentLink, false, cancellationToken).ConfigureAwait(false);
return application?.Name ?? string.Empty;
}
return string.Empty;
}
Quite nice to have the service provider available and full async support.
Typically, I've put these as C# default interface methods.
At first, I didn't see that this worked in the queries constructed off the IGraphContentClient from the Optimizely.Graph.Cms.Query package (the Graph C# SDK).
But I then was informed that the parser can handle .Result on async computed fields.
This is code that won't be executed at query time, it is only parsed and converted to GraphQL.
Code quality tools, like some Roslyn analyzers and others, will complain on this strong code smell, so you need to silence them when .Result is used in IGraphContentClient queries. I haven't found a better way than something like this:
var search = this.graphClient.QueryContent<ISomeContent>()
.Skip(skip)
.Limit(take)
.IncludeTotal();
if (applicationNames != null && applicationNames.Any())
{
#pragma warning disable MA0032 // Use an overload with a CancellationToken argument, even when no token is available in scope
#pragma warning disable VSTHRD002 // Avoid problematic synchronous waits
#pragma warning disable MA0045 // Do not use blocking calls, even when the calling method must become async
search = search.Where(x => x.SearchApplicationName().Result.In(applicationNames));
#pragma warning restore MA0045 // Do not use blocking calls, even when the calling method must become async
#pragma warning restore VSTHRD002 // Avoid problematic synchronous waits
#pragma warning restore MA0032 // Use an overload with a CancellationToken argument, even when no token is available in scope
}Published and tagged with these categories: Optimizely