Reorganizing the structure of the project, adding unit testing, adding PokemonService and ShakespeareService.

This commit is contained in:
2020-11-22 18:38:59 +01:00
parent 6c5d77d696
commit d47641ccb4
26 changed files with 353 additions and 86 deletions

View File

@ -0,0 +1,10 @@
using Pokespearean.Models.Generic;
using System.Threading.Tasks;
namespace Pokespearean.Services
{
public interface IPokemonService
{
Task<WebResult> GetPokemonDescription(string pokemonName);
}
}

View File

@ -0,0 +1,10 @@
using Pokespearean.Models.Generic;
using System.Threading.Tasks;
namespace Pokespearean.Services
{
public interface IShakespeareService
{
Task<WebResult> ToShakespearean(string text);
}
}

View File

@ -0,0 +1,38 @@
using PokeApiNet;
using Pokespearean.Models.Generic;
using System;
using System.Threading.Tasks;
using System.Linq;
namespace Pokespearean.Services
{
public class PokemonService : IPokemonService
{
private readonly PokeApiClient pokeApiClient;
public PokemonService()
{
pokeApiClient = new PokeApiClient();
}
public async Task<WebResult> GetPokemonDescription(string pokemonName)
{
var result = new WebResult();
try
{
var pokemonSpecies = await pokeApiClient.GetResourceAsync<PokemonSpecies>(pokemonName);
var hasRubyVersion = pokemonSpecies.FlavorTextEntries.Where(fte => fte.Language.Name == "en" && fte.Version.Name == "ruby").Any();
result.Data = pokemonSpecies.FlavorTextEntries
.FirstOrDefault(fte => (hasRubyVersion ? fte.Version.Name == "ruby" : true) && fte.Language.Name == "en")?
.FlavorText?.Replace("\n", " ")?.Replace("\f", " ");
return result;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return result.Invalidate(ex.Message, ex);
}
}
}
}

View File

@ -0,0 +1,43 @@
using Pokespearean.Models.Generic;
using System;
using System.Threading.Tasks;
using Pokespearean.Models;
using Pokespearean.Models.Shakespeare;
using Flurl;
using Flurl.Http;
using Microsoft.Extensions.Options;
namespace Pokespearean.Services
{
public class ShakespeareService : IShakespeareService
{
private string shakespeareApi;
public ShakespeareService(IOptions<Settings> settingsOption)
{
shakespeareApi = settingsOption.Value.ShakespeareApi;
}
public async Task<WebResult> ToShakespearean(string text)
{
var result = new WebResult();
try
{
var response = await shakespeareApi
.AppendPathSegment("translate")
.AppendPathSegment("shakespeare.json")
.SetQueryParam(nameof(text), text, isEncoded: true)
.GetJsonAsync<ShakespearResponse>();
result.Data = response.Contents.Translated;
return result;
}
catch (System.Exception ex)
{
Console.WriteLine(ex.Message);
return result.Invalidate(ex.Message, ex);
}
}
}
}