Made Book Metadata accessible in a non nested
This commit is contained in:
parent
2abb44408a
commit
073113a144
54
src/main.rs
54
src/main.rs
|
|
@ -5,37 +5,40 @@ use std::io;
|
|||
use std::str::from_utf8;
|
||||
use std::time::Duration;
|
||||
|
||||
#[derive(Debug)]
|
||||
struct BookData {
|
||||
title: String,
|
||||
authors: Vec<String>,
|
||||
thumbnail: String,
|
||||
description: String,
|
||||
}
|
||||
|
||||
#[allow(unused)]
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct BookRoot {
|
||||
items: Vec<Item>,
|
||||
}
|
||||
|
||||
#[allow(unused)]
|
||||
#[allow(unused, non_snake_case)]
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct Item {
|
||||
volumeinfo: VolumeInfo,
|
||||
volumeInfo: VolumeInfo,
|
||||
}
|
||||
|
||||
#[allow(unused)]
|
||||
#[allow(unused, non_snake_case)]
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct VolumeInfo {
|
||||
title: String,
|
||||
authors: Option<Vec<String>>,
|
||||
description: Option<String>,
|
||||
imagelinks: Option<ImageLinks>,
|
||||
imageLinks: Option<ImageLinks>,
|
||||
}
|
||||
|
||||
#[allow(unused)]
|
||||
#[allow(unused, non_snake_case)]
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct ImageLinks {
|
||||
thumbnail: Option<String>,
|
||||
smallThumbnail: Option<String>,
|
||||
}
|
||||
|
||||
#[tokio::main]
|
||||
|
|
@ -80,5 +83,44 @@ async fn get_book_data(isbn: String) {
|
|||
.json::<BookRoot>()
|
||||
.await
|
||||
.unwrap();
|
||||
println!("{:?}", book_data);
|
||||
let book_metadata: Vec<BookData> = book_data.items.into_iter().map(BookData::from).collect();
|
||||
println!("{}", &book_metadata[0]);
|
||||
}
|
||||
|
||||
impl From<Item> for BookData {
|
||||
fn from(item: Item) -> Self {
|
||||
let info = item.volumeInfo;
|
||||
BookData {
|
||||
title: info.title,
|
||||
authors: info.authors.unwrap_or_default(),
|
||||
description: info.description.as_deref().unwrap_or("").to_string(),
|
||||
thumbnail: info
|
||||
.imageLinks
|
||||
.as_ref()
|
||||
.and_then(|links| links.thumbnail.as_deref())
|
||||
.unwrap_or("")
|
||||
.to_string(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Display for BookData {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(
|
||||
f,
|
||||
"Title: {}\nAuthors: {}\nDescription: {}\nThumbnail: {}",
|
||||
self.title,
|
||||
if self.authors.is_empty() {
|
||||
"Unknown".to_string()
|
||||
} else {
|
||||
self.authors.join(", ")
|
||||
},
|
||||
if self.description.is_empty() {
|
||||
"No description available".to_string()
|
||||
} else {
|
||||
self.description.clone()
|
||||
},
|
||||
self.thumbnail
|
||||
)
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in a new issue