⚡ Translation now with cache
This commit is contained in:
@@ -1,4 +1,7 @@
|
|||||||
using DysonNetwork.Pass.Account;
|
using DysonNetwork.Pass.Account;
|
||||||
|
using System.Security.Cryptography;
|
||||||
|
using System.Text;
|
||||||
|
using DysonNetwork.Shared.Cache;
|
||||||
using Microsoft.AspNetCore.Authorization;
|
using Microsoft.AspNetCore.Authorization;
|
||||||
using Microsoft.AspNetCore.Mvc;
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
|
||||||
@@ -6,8 +9,17 @@ namespace DysonNetwork.Sphere.Translation;
|
|||||||
|
|
||||||
[ApiController]
|
[ApiController]
|
||||||
[Route("/api/translate")]
|
[Route("/api/translate")]
|
||||||
public class TranslationController(ITranslationProvider provider) : ControllerBase
|
public class TranslationController(ITranslationProvider provider, ICacheService cache) : ControllerBase
|
||||||
{
|
{
|
||||||
|
private const string CacheKeyPrefix = "translation:";
|
||||||
|
|
||||||
|
private static string GenerateCacheKey(string text, string targetLanguage)
|
||||||
|
{
|
||||||
|
var inputBytes = Encoding.UTF8.GetBytes($"{text}:{targetLanguage}");
|
||||||
|
var hashBytes = SHA256.HashData(inputBytes);
|
||||||
|
return $"{CacheKeyPrefix}{Convert.ToHexString(hashBytes)}";
|
||||||
|
}
|
||||||
|
|
||||||
[HttpPost]
|
[HttpPost]
|
||||||
[Authorize]
|
[Authorize]
|
||||||
public async Task<ActionResult<string>> Translate([FromBody] string text, [FromQuery(Name = "lang")] string targetLanguage)
|
public async Task<ActionResult<string>> Translate([FromBody] string text, [FromQuery(Name = "lang")] string targetLanguage)
|
||||||
@@ -15,7 +27,22 @@ public class TranslationController(ITranslationProvider provider) : ControllerBa
|
|||||||
if (HttpContext.Items["CurrentUser"] is not Account currentUser) return Unauthorized();
|
if (HttpContext.Items["CurrentUser"] is not Account currentUser) return Unauthorized();
|
||||||
if (currentUser.PerkSubscription is null)
|
if (currentUser.PerkSubscription is null)
|
||||||
return StatusCode(403, "You need a subscription to use this feature.");
|
return StatusCode(403, "You need a subscription to use this feature.");
|
||||||
|
|
||||||
return await provider.Translate(text, targetLanguage);
|
// Generate cache key
|
||||||
|
var cacheKey = GenerateCacheKey(text, targetLanguage);
|
||||||
|
|
||||||
|
// Try to get from cache first
|
||||||
|
var (found, cachedResult) = await cache.GetAsyncWithStatus<string>(cacheKey);
|
||||||
|
if (found && cachedResult != null)
|
||||||
|
return Ok(cachedResult);
|
||||||
|
|
||||||
|
// If not in cache, translate and cache the result
|
||||||
|
var result = await provider.Translate(text, targetLanguage);
|
||||||
|
if (!string.IsNullOrEmpty(result))
|
||||||
|
{
|
||||||
|
await cache.SetAsync(cacheKey, result, TimeSpan.FromHours(24)); // Cache for 24 hours
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
}
|
}
|
||||||
}
|
}
|
Reference in New Issue
Block a user