|
| 1 | +using CodeBeam.UltimateAuth.Core.Contracts; |
| 2 | +using Microsoft.AspNetCore.Components.WebAssembly.Http; |
| 3 | +using System.Net.Http.Json; |
| 4 | + |
| 5 | +namespace CodeBeam.UltimateAuth.Sample.BlazorStandaloneWasm.ResourceApi; |
| 6 | + |
| 7 | +public class ProductApiService |
| 8 | +{ |
| 9 | + private readonly HttpClient _http; |
| 10 | + |
| 11 | + public ProductApiService(HttpClient http) |
| 12 | + { |
| 13 | + _http = http; |
| 14 | + } |
| 15 | + |
| 16 | + private HttpRequestMessage CreateRequest(HttpMethod method, string url, object? body = null) |
| 17 | + { |
| 18 | + var request = new HttpRequestMessage(method, url); |
| 19 | + request.SetBrowserRequestCredentials(BrowserRequestCredentials.Include); |
| 20 | + |
| 21 | + if (body is not null) |
| 22 | + { |
| 23 | + request.Content = JsonContent.Create(body); |
| 24 | + } |
| 25 | + |
| 26 | + return request; |
| 27 | + } |
| 28 | + |
| 29 | + public Task<UAuthResult<List<SampleProduct>>> GetAllAsync() |
| 30 | + => SendAsync<List<SampleProduct>>(CreateRequest(HttpMethod.Get, "/api/products")); |
| 31 | + |
| 32 | + public Task<UAuthResult<SampleProduct?>> GetAsync(int id) |
| 33 | + => SendAsync<SampleProduct?>(CreateRequest(HttpMethod.Get, $"/api/products/{id}")); |
| 34 | + |
| 35 | + public Task<UAuthResult<SampleProduct?>> CreateAsync(SampleProduct product) |
| 36 | + => SendAsync<SampleProduct?>(CreateRequest(HttpMethod.Post, $"/api/products", product)); |
| 37 | + |
| 38 | + public Task<UAuthResult<SampleProduct?>> UpdateAsync(int id, SampleProduct product) |
| 39 | + => SendAsync<SampleProduct?>(CreateRequest(HttpMethod.Put, $"/api/products/{id}", product)); |
| 40 | + |
| 41 | + public Task<UAuthResult<SampleProduct?>> DeleteAsync(int id) |
| 42 | + => SendAsync<SampleProduct?>(CreateRequest(HttpMethod.Delete, $"/api/products/{id}")); |
| 43 | + |
| 44 | + private async Task<UAuthResult<T>> SendAsync<T>(HttpRequestMessage request) |
| 45 | + { |
| 46 | + var response = await _http.SendAsync(request); |
| 47 | + |
| 48 | + var result = new UAuthResult<T> |
| 49 | + { |
| 50 | + Status = (int)response.StatusCode, |
| 51 | + IsSuccess = response.IsSuccessStatusCode |
| 52 | + }; |
| 53 | + |
| 54 | + if (response.IsSuccessStatusCode) |
| 55 | + { |
| 56 | + result.Value = await response.Content.ReadFromJsonAsync<T>(); |
| 57 | + return result; |
| 58 | + } |
| 59 | + |
| 60 | + result.Problem = await TryReadProblem(response); |
| 61 | + return result; |
| 62 | + } |
| 63 | + |
| 64 | + private async Task<UAuthProblem?> TryReadProblem(HttpResponseMessage response) |
| 65 | + { |
| 66 | + try |
| 67 | + { |
| 68 | + return await response.Content.ReadFromJsonAsync<UAuthProblem>(); |
| 69 | + } |
| 70 | + catch |
| 71 | + { |
| 72 | + return new UAuthProblem |
| 73 | + { |
| 74 | + Title = response.ReasonPhrase |
| 75 | + }; |
| 76 | + } |
| 77 | + } |
| 78 | +} |
0 commit comments