Created
May 14, 2020 04:29
-
-
Save JeremyLikness/b73ec9f54983a4d4e204faafd06511ee to your computer and use it in GitHub Desktop.
A blog client that retries credentials
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
using BlazorCosmosWasm.Shared; | |
using Microsoft.EntityFrameworkCore; | |
using System; | |
using System.Net.Http; | |
using System.Net.Http.Json; | |
using System.Threading.Tasks; | |
namespace BlazorCosmosWasm.Client.Data | |
{ | |
public class BlogClient : IBlogClient | |
{ | |
private CosmosCredentials Credentials; | |
private readonly HttpClient Http; | |
public BlogClient(HttpClient client) | |
{ | |
Http = client; | |
} | |
public async Task<BlogContext> GetDbContextAsync() | |
{ | |
if (Credentials == null) | |
{ | |
await GetCredentialsAsync(); | |
} | |
BlogContext context = null; | |
CosmosCredentials getCredentials() => Credentials; | |
var options = new DbContextOptionsBuilder<BlogContext>() | |
.UseCosmos(getCredentials().EndPoint, getCredentials().Key, BlogContext.DatabaseName, | |
opt => | |
opt.ConnectionMode(Microsoft.Azure.Cosmos.ConnectionMode.Gateway)); | |
try | |
{ | |
context = new BlogContext(options.Options); | |
} | |
catch | |
{ | |
// try again with fresh credentials | |
await GetCredentialsAsync(); | |
context = new BlogContext(options.Options); | |
} | |
return context; | |
} | |
private async Task GetCredentialsAsync() | |
{ | |
Credentials = await Http.GetFromJsonAsync<CosmosCredentials>("api/Cosmos"); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment