Created
May 21, 2023 13:04
-
-
Save AndyButland/ecf2195d218f53205430751b471f998a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public async Task<CollectionResult<PackageDto>> GetPackages(PackageSearchQuery query) | |
{ | |
if (!IsSearchServiceConfigured()) | |
{ | |
return CollectionResult<PackageDto>.Empty(); | |
} | |
SearchClient searchClient = GetSearchClient(); | |
string searchText = GetSearchText(query); | |
SearchOptions searchOptions = GetSearchOptions(query); | |
Response<SearchResults<PackageModel>> resultsResponse; | |
try | |
{ | |
resultsResponse = await searchClient.SearchAsync<PackageModel>(searchText, searchOptions); | |
} | |
catch (RequestFailedException ex) when (ex.Message.StartsWith("If a query contains the search option the target index must contain one or more searchable string fields.")) | |
{ | |
// No fields defined on index (i.e. not yet populated). | |
return CollectionResult<PackageDto>.Empty(); | |
} | |
SearchResults<PackageModel> results = resultsResponse.Value; | |
return CollectionResult<PackageDto>.FromResults( | |
results.GetResults() | |
.Select(x => x.Document.ToPackageDto(query)), | |
results.TotalCount ?? 0); | |
} | |
private bool IsSearchServiceConfigured() => !string.IsNullOrWhiteSpace(_searchSettings.ServiceEndPoint); | |
private SearchClient GetSearchClient() | |
{ | |
if (string.IsNullOrEmpty(_searchSettings.QueryApiKey)) | |
{ | |
throw new InvalidOperationException($"Cannot create a search client operations as the query API key was not provided."); | |
} | |
return new SearchClient(new Uri(_searchSettings.ServiceEndPoint), _searchSettings.IndexName, new AzureKeyCredential(_searchSettings.QueryApiKey)); | |
} | |
private static string GetSearchText(PackageSearchQuery query) => string.IsNullOrEmpty(query.Text) ? "*" : query.Text; | |
private static SearchOptions GetSearchOptions(PackageSearchQuery query) | |
{ | |
var options = new SearchOptions | |
{ | |
IncludeTotalCount = true, | |
}; | |
SelectFields(options, query); | |
ApplyFilter(options, query); | |
ApplyOrderBy(options, query); | |
ApplyPaging(query, options); | |
return options; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment