Get credits remaining at startup and after changing the API key

This commit is contained in:
Robert 2024-07-06 21:01:07 -07:00
parent aa0a74d4dc
commit 6399693e09
2 changed files with 58 additions and 3 deletions

View File

@ -20,6 +20,27 @@ public partial class ClientForm : Form
this.clientFormConfiguration = this.clientFormConfigurationManager.Load();
this.apiKeyTextBox.Text = this.clientFormConfiguration.ApiKey;
this.UpdateCreditBalanceAsync();
}
protected async void UpdateCreditBalanceAsync()
{
this.SetEnabled(false);
try
{
var creditBalance = await this.keywordsEverywhereApi.GetCreditBalanceAsync(this.clientFormConfiguration.ApiKey, default);
this.UpdateCreditsRemaining(creditBalance);
}
catch
{
creditsRemainingLabel.Text = "Credits remaining: TBD";
}
finally
{
this.SetEnabled(true);
}
}
protected override void OnShown(EventArgs e)
@ -32,8 +53,13 @@ public partial class ClientForm : Form
private void apiKeyTextBox_Leave(object sender, EventArgs e)
{
this.clientFormConfiguration.ApiKey = this.apiKeyTextBox.Text;
this.clientFormConfigurationManager.Save(this.clientFormConfiguration);
if (this.clientFormConfiguration.ApiKey != this.apiKeyTextBox.Text)
{
this.clientFormConfiguration.ApiKey = this.apiKeyTextBox.Text;
this.clientFormConfigurationManager.Save(this.clientFormConfiguration);
this.UpdateCreditBalanceAsync();
}
}
private async void getResultsButton_Click(object sender, EventArgs e)
@ -89,7 +115,12 @@ public partial class ClientForm : Form
this.resultsDataGrid.DataSource = rows;
creditsRemainingLabel.Text = $"Credits remaining: {responseData.Credits}";
UpdateCreditsRemaining(responseData.Credits);
}
private void UpdateCreditsRemaining(long creditsRemaining)
{
creditsRemainingLabel.Text = $"Credits remaining: {creditsRemaining}";
}
private void HandleError(GetKeywordDataError errorData)

View File

@ -14,6 +14,30 @@ internal class KeywordsEverywhereApi
});
}
public async Task<long> GetCreditBalanceAsync(string apiKey, CancellationToken cancellationToken)
{
HttpRequestMessage request = new(HttpMethod.Get, "https://api.keywordseverywhere.com/v1/account/credits");
request.Headers.Add("Accept", "application/json");
request.Headers.Add("Authorization", $"Bearer {apiKey}");
using var response = await this.httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken);
var responseBody = await response.Content.ReadAsStringAsync(cancellationToken);
if (response.IsSuccessStatusCode)
{
var result = JsonSerializer.Deserialize<IReadOnlyList<long>>(responseBody)
?? throw new InvalidOperationException("Success response is null.");
return result.Single();
}
else
{
throw new InvalidOperationException("Failed to get credit balance. " + responseBody);
}
}
public async Task<GetKeywordResponseOrError> GetKeywordDataAsync(string apiKey, GetKeywordDataRequest requestData, CancellationToken cancellationToken)
{
HttpRequestMessage request = new(HttpMethod.Post, "https://api.keywordseverywhere.com/v1/get_keyword_data");