refactor: introduce lightweight hexagonal layout

This commit is contained in:
2026-06-13 06:42:35 +02:00
parent 6fc5cc1bc8
commit aa3b678cc5
9 changed files with 46 additions and 35 deletions

View File

@@ -0,0 +1,136 @@
use crate::{domain::TranslationKind, error::AppError};
use serde::Deserialize;
use std::time::Duration;
use tracing::instrument;
#[derive(Clone)]
pub struct TranslationClient {
base_url: String,
http: reqwest::Client,
}
impl TranslationClient {
pub fn new(base_url: impl Into<String>, timeout: Duration) -> Result<Self, AppError> {
let http = reqwest::Client::builder()
.timeout(timeout)
.build()
.map_err(|error| AppError::Upstream(error.to_string()))?;
Ok(Self {
base_url: trim_trailing_slash(&base_url.into()),
http,
})
}
#[instrument(skip(self, text), fields(translation.kind = ?kind))]
pub async fn translate(&self, kind: TranslationKind, text: &str) -> Result<String, AppError> {
let url = format!("{}/translate/{}.json", self.base_url, endpoint_for(kind));
let response = self
.http
.post(url)
.form(&[("text", text)])
.send()
.await
.map_err(|error| map_reqwest_error(&error))?;
let status = response.status();
if !status.is_success() {
return Err(AppError::Upstream(format!(
"FunTranslations returned status {status}"
)));
}
response
.json::<TranslationResponse>()
.await
.map(|payload| payload.contents.translated)
.map_err(|error| map_reqwest_error(&error))
}
}
#[derive(Debug, Deserialize)]
struct TranslationResponse {
contents: TranslationContents,
}
#[derive(Debug, Deserialize)]
struct TranslationContents {
translated: String,
}
const fn endpoint_for(kind: TranslationKind) -> &'static str {
match kind {
TranslationKind::Shakespeare => "shakespeare",
TranslationKind::Yoda => "yoda",
}
}
fn trim_trailing_slash(value: &str) -> String {
value.trim_end_matches('/').to_owned()
}
fn map_reqwest_error(error: &reqwest::Error) -> AppError {
if error.is_timeout() {
AppError::Timeout
} else {
AppError::Upstream(error.to_string())
}
}
#[cfg(test)]
mod tests {
use super::{TranslationClient, endpoint_for};
use crate::domain::TranslationKind;
use std::time::Duration;
use wiremock::{Mock, MockServer, ResponseTemplate, matchers};
#[test]
fn translation_kind_resolves_funtranslations_endpoint() {
assert_eq!(endpoint_for(TranslationKind::Yoda), "yoda");
assert_eq!(endpoint_for(TranslationKind::Shakespeare), "shakespeare");
}
#[tokio::test]
async fn posts_text_to_the_requested_translation_endpoint() {
let server = MockServer::start().await;
Mock::given(matchers::method("POST"))
.and(matchers::path("/translate/yoda.json"))
.and(matchers::body_string_contains("text=Created"))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
"contents": { "translated": "Created, it was." }
})))
.expect(1)
.mount(&server)
.await;
let client = client_for(&server);
let translated = client
.translate(TranslationKind::Yoda, "Created")
.await
.expect("translation should succeed");
assert_eq!(translated, "Created, it was.");
}
#[tokio::test]
async fn maps_translation_http_failures_to_upstream_errors() {
let server = MockServer::start().await;
Mock::given(matchers::method("POST"))
.and(matchers::path("/translate/shakespeare.json"))
.respond_with(ResponseTemplate::new(429))
.mount(&server)
.await;
let client = client_for(&server);
let error = client
.translate(TranslationKind::Shakespeare, "hello")
.await
.expect_err("translation should fail");
assert!(error.to_string().contains("FunTranslations"));
}
fn client_for(server: &MockServer) -> TranslationClient {
TranslationClient::new(server.uri(), Duration::from_secs(1)).expect("client should build")
}
}