|
| 1 | +using Microsoft.AspNetCore.Components.WebAssembly.Http; |
| 2 | +using System.Net.Http.Json; |
| 3 | + |
| 4 | +namespace CodeBeam.UltimateAuth.Sample.BlazorStandaloneWasm.ResourceApi; |
| 5 | + |
| 6 | +public class ProductApiService |
| 7 | +{ |
| 8 | + private readonly HttpClient _http; |
| 9 | + |
| 10 | + public ProductApiService(HttpClient http) |
| 11 | + { |
| 12 | + _http = http; |
| 13 | + } |
| 14 | + |
| 15 | + public async Task<List<Product>> GetAllAsync() |
| 16 | + { |
| 17 | + var request = new HttpRequestMessage(HttpMethod.Get, "/api/products"); |
| 18 | + request.SetBrowserRequestCredentials(BrowserRequestCredentials.Include); |
| 19 | + |
| 20 | + var response = await _http.SendAsync(request); |
| 21 | + |
| 22 | + if (!response.IsSuccessStatusCode) |
| 23 | + throw new Exception($"Failed to fetch products: {response.StatusCode}"); |
| 24 | + |
| 25 | + return await response.Content.ReadFromJsonAsync<List<Product>>() ?? new(); |
| 26 | + } |
| 27 | + |
| 28 | + public async Task<Product?> GetAsync(int id) |
| 29 | + { |
| 30 | + var response = await _http.GetAsync($"/api/products/{id}"); |
| 31 | + |
| 32 | + if (!response.IsSuccessStatusCode) |
| 33 | + return null; |
| 34 | + |
| 35 | + return await response.Content.ReadFromJsonAsync<Product>(); |
| 36 | + } |
| 37 | + |
| 38 | + public async Task<Product?> CreateAsync(Product product) |
| 39 | + { |
| 40 | + var response = await _http.PostAsJsonAsync("/api/products", product); |
| 41 | + |
| 42 | + if (!response.IsSuccessStatusCode) |
| 43 | + throw new Exception($"Create failed: {response.StatusCode}"); |
| 44 | + |
| 45 | + return await response.Content.ReadFromJsonAsync<Product>(); |
| 46 | + } |
| 47 | + |
| 48 | + public async Task DeleteAsync(int id) |
| 49 | + { |
| 50 | + var response = await _http.DeleteAsync($"/api/products/{id}"); |
| 51 | + |
| 52 | + if (!response.IsSuccessStatusCode) |
| 53 | + throw new Exception($"Delete failed: {response.StatusCode}"); |
| 54 | + } |
| 55 | +} |
0 commit comments