#445 list of poets

This commit is contained in:
Hamid Reza Mohammadi 2024-07-19 14:30:37 +03:30
parent 68aa795e1a
commit 95e4bf370f
3 changed files with 75 additions and 7 deletions

View File

@ -5,6 +5,9 @@
}
<div class="text-center">
<h1 class="display-4">Welcome</h1>
<p>Learn about <a href="https://learn.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p>
<h1 class="display-4">Ганҷур</h1>
@foreach(var poet in Model.Poets)
{
<p><a href="@poet.FullUrl">@poet.Nickname</a></p>
}
</div>

View File

@ -1,28 +1,89 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Caching.Memory;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using RMuseum.Models.Ganjoor.ViewModels;
namespace TajikGanjoor.Pages
{
public class IndexModel : PageModel
{
public IActionResult OnGet()
public List<GanjoorPoetViewModel> Poets { get; set; }
public async Task<IActionResult> OnGetAsync()
{
if (bool.Parse(Configuration["MaintenanceMode"] ?? false.ToString()))
{
return StatusCode(503);
}
if(false == await PreparePoetsAsync())
{
return Page();
}
return Page();
}
protected readonly IConfiguration Configuration;
private async Task<bool> PreparePoetsAsync()
{
var cacheKey = $"/api/ganjoor/poets";
if (!_memoryCache.TryGetValue(cacheKey, out List<GanjoorPoetViewModel>? poets))
{
try
{
var response = await _httpClient.GetAsync($"{APIRoot.Url}/api/ganjoor/poets");
if (!response.IsSuccessStatusCode)
{
LastError = JsonConvert.DeserializeObject<string>(await response.Content.ReadAsStringAsync()) ?? "!response.IsSuccessStatusCode";
return false;
}
poets = JArray.Parse(await response.Content.ReadAsStringAsync()).ToObject<List<GanjoorPoetViewModel>>();
if (AggressiveCacheEnabled)
{
_memoryCache.Set(cacheKey, poets);
}
}
catch
{
LastError = "خطا در دسترسی به وب سرویس گنجور";
return false;
}
}
Poets = poets ?? [];
return true;
}
public string LastError { get; set; }
public bool AggressiveCacheEnabled
{
get
{
try
{
return bool.Parse(Configuration["AggressiveCacheEnabled"] ?? false.ToString());
}
catch
{
return false;
}
}
}
protected readonly IConfiguration Configuration;
protected readonly HttpClient _httpClient;
public IndexModel(IConfiguration configuration, HttpClient httpClient)
private readonly IMemoryCache _memoryCache;
public IndexModel(IConfiguration configuration, HttpClient httpClient, IMemoryCache memoryCache)
{
Configuration = configuration;
_httpClient = httpClient;
_memoryCache = memoryCache;
}
}
}

View File

@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<TargetFramework>net8.0-windows</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
@ -10,4 +10,8 @@
<PackageReference Include="GoogleTranslateFreeApi" Version="1.1.1" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\RMuseum\RMuseum.csproj" />
</ItemGroup>
</Project>