new struct for response

master
Mathias Rothenhaeusler 2021-09-18 22:20:43 +02:00
parent 00e2913b7a
commit 60d011a5db
2 changed files with 30 additions and 15 deletions

View File

@ -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<Translations>,
}
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
}
}
}

View File

@ -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<dyn std::error::Error>> {
@ -21,12 +21,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
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(())
}