From 60d011a5dbe99ff52cb2e76e47f5886ef727b3b6 Mon Sep 17 00:00:00 2001 From: mace Date: Sat, 18 Sep 2021 22:20:43 +0200 Subject: [PATCH] new struct for response --- src/lib.rs | 30 +++++++++++++++++++++++++----- src/main.rs | 15 +++++---------- 2 files changed, 30 insertions(+), 15 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 81443f1..e43b570 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -2,8 +2,9 @@ pub mod deepl_helper { use clap::{load_yaml, App}; use directories::BaseDirs; use dotenv; + use serde::{Deserialize, Serialize}; use sprintf::sprintf; - use std::env::{self}; + use std::{env::{self}}; pub struct Params { source_lang: String, @@ -34,10 +35,7 @@ pub mod deepl_helper { Self { source_lang: matches.value_of("source").unwrap_or("DE").to_string(), - target_lang: matches - .value_of("target") - .unwrap_or("EN-US") - .to_string(), + target_lang: matches.value_of("target").unwrap_or("EN-US").to_string(), file: matches.value_of("file").unwrap_or_default().to_string(), key: env::var("key").unwrap(), uri: env::var("uri").unwrap(), @@ -60,4 +58,26 @@ pub mod deepl_helper { .unwrap() } } + + #[derive(Serialize, Deserialize, Default)] + struct Translations { + detected_source_language: String, + text: String, + } + + #[derive(Serialize, Deserialize)] + pub struct DeeplResponse { + translations: Vec, + } + + impl DeeplResponse { + pub fn get_text(&self) -> String { + let mut trans = "\n".to_string(); + for translation in self.translations.iter() { + trans.push_str(&translation.text); + trans.push_str("\n"); + } + trans + } + } } diff --git a/src/main.rs b/src/main.rs index 91f58ea..010b3c5 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,9 +1,9 @@ -use std::str::FromStr; -use deepl::deepl_helper::Params; + +use deepl::deepl_helper::{DeeplResponse, Params}; use hyper::{Body, Client, Method, Request, body}; use hyper_tls::HttpsConnector; -use serde_json::Value; + #[tokio::main(flavor = "current_thread")] async fn main() -> Result<(), Box> { @@ -21,12 +21,7 @@ async fn main() -> Result<(), Box> { let res = client.request(request).await?; let body_bytes = body::to_bytes(res.into_body()).await?; let body = String::from_utf8(body_bytes.to_vec()).expect("response was not valid utf-8"); - let v: Value = serde_json::from_str(&body)?; - let result = String::from_str(match v["translations"][0]["text"].as_str() { - Some(text) => text, - None => body.as_str() - }).unwrap(); - - println!("{}", result.replace("\"", "")); + let v: DeeplResponse = serde_json::from_str(&body)?; + println!("{}", v.get_text()); Ok(()) }