Created
December 11, 2019 22:42
-
-
Save urffin/dd7248fb801ed428cbd984226fe27a77 to your computer and use it in GitHub Desktop.
sample refactoring
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 interface IApiClient | |
{ | |
Task<T> Call<T>(string uri, object request, CancellationToken cancellationToken); | |
Task<string> GetToken(); | |
} | |
public class ApiClient: IApiClient | |
{ | |
protected ApiClient() | |
{ | |
Client = new HttpClient(); | |
} | |
private HttpClient Client { get; } | |
private const string BaseUrl = "https://server.tld"; | |
private const string ServiceAccountUserName = "user"; | |
private const string ServiceAccountUserPassword = "password"; | |
public async Task<T> Call<T>(string uri, object request, CancellationToken cancellationToken) | |
{ | |
var token = await GetToken(); | |
var result = await Post<T>(uri, request, token); | |
return result; | |
} | |
private async Task<TResponse> Post<TResponse>(string uri, object request, string token = null) | |
{ | |
var jsonString = JsonConvert.SerializeObject(request); | |
var content = new StringContent(jsonString, Encoding.UTF8, "application/json"); | |
if (!string.IsNullOrWhiteSpace(token)) | |
{ | |
Client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); | |
} | |
var response = await Client.PostAsync(uri, content); | |
var result = await response.Content.ReadAsStringAsync(); | |
var deserialized = JsonConvert.DeserializeObject<TResponse>(result); | |
return deserialized; | |
} | |
public async Task<string> GetToken() | |
{ | |
var request = new TokenRequest | |
{ | |
UserName = ServiceAccountUserName, | |
Password = ServiceAccountUserPassword, | |
}; | |
const string url = "/api/token"; | |
var answer = await Post<TokenAnwer>(url, request); | |
return answer.Token; | |
} | |
private class TokenRequest | |
{ | |
public string UserName { get; set; } | |
public string Password { get; set; } | |
} | |
public class TokenAnwer | |
{ | |
public string Token { get; set; } | |
//public string UserName { get; set; } | |
} | |
} | |
public class CacheTokenApiClient : IApiClient | |
{ | |
private readonly ApiClient apiClient; | |
public CacheTokenApiClient(ApiClient apiClient) | |
{ | |
this.apiClient = apiClient; | |
} | |
public Task<T> Call<T>(string uri, object request, CancellationToken cancellationToken) | |
{ | |
return apiClient.Call<T>(uri, request, cancellationToken); | |
} | |
private string token; | |
public async Task<string> GetToken() | |
{ | |
if (!string.IsNullOrEmpty(token)) | |
{ | |
return token; | |
} | |
token = await apiClient.GetToken(); | |
return token; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment