簡體   English   中英

將數據序列化為結構 model,其中兩個字段的數據是根據結構中的其他字段計算的

[英]Serialize data into struct model, where two of those fields' data are calculated based upon other fields in the struct

我這里有一個 model:

#[derive(Debug, Serialize, Deserialize)]
pub struct ArticleModel {
        #[serde(rename = "_id", skip_serializing_if = "Option::is_none")]
        pub id: Option<ObjectId>,
        pub text: String,
        pub author: String,
        pub edited_date: Option<DateTime<Utc>>,
        pub posted_date: Option<DateTime<Utc>>,
        pub is_archived: bool,
        pub tags: Vec<String>,
        pub read_time_in_min: i32, // <-- Take note of this field
        pub word_count: i32, // <-- Take note of this field
    }

在我的 api 處理程序中,我嘗試將請求的主體轉換為如下所示:

#[post("/article")]
pub async fn create_article(
    data: Data<ArticleRepo>,
    new_article: Json<ArticleModel>, // <-- HERE, using Json extractor
) -> HttpResponse {
    let mut created_article = new_article.into_inner(); // <-- HERE getting its value
    created_article.id = None;

    let article_detail = data.create_article_repo(created_article).await;

    match article_detail {
        Ok(article) => HttpResponse::Ok().json(article),
        Err(err) => HttpResponse::InternalServerError().body(err.to_string()),
    }
}

除此之外,我不想在請求正文中傳遞字段read_time_in_minword_count 我試圖根據text字段的內容計算它們。 這些函數將&text作為輸入,將i32和 i32 作為輸入。

我無法弄清楚如何布置這個。 我想創建一個ArticleModel impl塊,它有一個關聯的new function 接受所需的參數,然后輸出一個具有計算值的Self的新實例,除了,然后,我無法從我的處理程序中反序列化ArticleModel ,因為我必須反序列化為struct並且不能在那里調用new的 function。 我也不會在請求正文中傳遞 2 個計算字段,這意味着它將返回 json 解析錯誤。

我該如何解決這個問題?

您可以將[serde(skip_deserializing)]屬性添加到read_time_in_minword_count ,這樣它們就不必包含在請求正文中。 您也可以將它們包裝在一個Option中,但這可能看起來更糟,並且還將允許用戶控制那些可能不理想的變量。

這是一個例子:

#[derive(Debug, Serialize, Deserialize)]
pub struct ArticleModel {
        #[serde(rename = "_id", skip_serializing_if = "Option::is_none")]
        pub id: Option<ObjectId>,
        pub text: String,
        pub author: String,
        pub edited_date: Option<DateTime<Utc>>,
        pub posted_date: Option<DateTime<Utc>>,
        pub is_archived: bool,
        pub tags: Vec<String>,
        #[serde(skip_deserializing)]
        pub read_time_in_min: i32, 
        #[serde(skip_deserializing)]
        pub word_count: i32,
    }

感謝@Kendas 從評論中獲得解決方案

我為類型ArticleModel實現了From特征,它轉換我在 api 處理程序中期望的新類型ArticleDeserializableModel ,並將其轉換為我在內部使用的可存儲ArticleModel ,然后允許我包括計算。

impl From<ArticleDeserializableModel> for ArticleModel {
    fn from(article_deserializable_model: ArticleDeserializableModel) -> ArticleModel {
        ArticleModel {
            id: None,
            text: article_deserializable_model.text.to_owned(),
            author: article_deserializable_model.author,
            edited_date: None,
            posted_date: None,
            is_archived: article_deserializable_model.is_archived,
            tags: article_deserializable_model.tags,
            read_time_in_min: ArticleModel::word_count_to_read_time_in_min(
                ArticleModel::count_words(&article_deserializable_model.text),
            ),
            word_count: ArticleModel::count_words(&article_deserializable_model.text),
        }
    }
} 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM