Search code examples
rustrust-rocket

get title from Zotero item


Still very new to Rust, trying to understand how to extract the title of a JournalArticle using the Zotero crate.

I've got this, and can confirm the item is retrieved successfully:

let zc = ZoteroCredentials::new();
let z = ZoteroInit::set_user(&zc.api_id, &zc.api_key);
let item = z.get_item(item_id, None).unwrap();

From here, I see that an item.data is an ItemType, specifically a JournalArticleData. But I'm fundamentally not quite understanding how to either a) serialize this to JSON, or b) access .title as a property.

For context, this would be the result of a Rocket GET route.

Any help would much appreciated!


Solution

  • It sounds like the part you're missing is how to use pattern matching on an enum. I'm not familiar with zotero so this is all based on the docs, with verbose type annotations to be explicit about what I think I'm doing:

    use zotero::data_structure::item::{Item, ItemType, JournalArticleData};
    
    let item: Item = z.get_item(item_id, None).unwrap();
    
    // Now we must extract the JournalArticle from the ItemType, which is an enum
    // and therefore requires pattern matching.
    let article: JournalArticleData = match item.data {
        ItemType::JournalArticle(a) => a,
        something_else => todo!("handle wrong type of item"),
    }
    
    let title: String = article.title;
    

    (The match could also be written as an if let just as well.)

    You could also use pattern matching to go through the entire structure, rather than only the enum which requires it:

    match z.get_item(item_id, None).unwrap() {
        Item {
            data: ItemType::JournalArticle(JournalArticleData {
                title,
                ..
            }),
            ..
        } => {
            // Use the `title` variable here
        },
        something_else => todo!("handle wrong type of item"),
    }