optimize code in searchsuggestions

This commit is contained in:
弘韬 张 2021-01-07 21:54:09 +08:00
parent 1003ce4160
commit c939924ec8
2 changed files with 11 additions and 22 deletions

View file

@ -17,12 +17,15 @@ namespace Flow.Launcher.Plugin.WebSearch.SuggestionSources
{
public override async Task<List<string>> Suggestions(string query, CancellationToken token)
{
Stream resultStream;
JsonElement json;
try
{
const string api = "https://api.bing.com/qsonhs.aspx?q=";
resultStream = await Http.GetStreamAsync(api + Uri.EscapeUriString(query), token).ConfigureAwait(false);
using var resultStream = await Http.GetStreamAsync(api + Uri.EscapeUriString(query), token).ConfigureAwait(false);
if (resultStream.Length == 0) return new List<string>(); // this handles the cancellation
json = (await JsonDocument.ParseAsync(resultStream, cancellationToken: token)).RootElement.GetProperty("AS");
}
catch (TaskCanceledException)
{
@ -33,15 +36,6 @@ namespace Flow.Launcher.Plugin.WebSearch.SuggestionSources
Log.Exception("|Bing.Suggestions|Can't get suggestion from Bing", e);
return new List<string>();
}
if (resultStream.Length == 0) return new List<string>(); // this handles the cancellation
JsonElement json;
try
{
using (resultStream)
json = (await JsonDocument.ParseAsync(resultStream)).RootElement.GetProperty("AS");
}
catch (JsonException e)
{
Log.Exception("|Bing.Suggestions|can't parse suggestions", e);

View file

@ -16,11 +16,15 @@ namespace Flow.Launcher.Plugin.WebSearch.SuggestionSources
{
public override async Task<List<string>> Suggestions(string query, CancellationToken token)
{
Stream resultStream;
JsonDocument json;
try
{
const string api = "https://www.google.com/complete/search?output=chrome&q=";
resultStream = await Http.GetStreamAsync(api + Uri.EscapeUriString(query)).ConfigureAwait(false);
using var resultStream = await Http.GetStreamAsync(api + Uri.EscapeUriString(query)).ConfigureAwait(false);
if (resultStream.Length == 0) return new List<string>();
json = await JsonDocument.ParseAsync(resultStream);
}
catch (TaskCanceledException)
{
@ -31,15 +35,6 @@ namespace Flow.Launcher.Plugin.WebSearch.SuggestionSources
Log.Exception("|Google.Suggestions|Can't get suggestion from google", e);
return new List<string>();
}
if (resultStream.Length == 0) return new List<string>();
JsonDocument json;
try
{
using (resultStream)
json = await JsonDocument.ParseAsync(resultStream);
}
catch (JsonException e)
{
Log.Exception("|Google.Suggestions|can't parse suggestions", e);