我这里有个模特:
#[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处理程序中,我try 将请求的正文转换为如下形式:
#[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_min
和word_count
.我正在试着根据text
字段的内容来计算它们.这些函数将&text
作为输入,并输出i32
.
我想不出该怎么解决这个问题.我曾考虑创建一个ArticleModel
impl
块,它有一个关联的new
函数,该函数接受所需的参数,然后输出一个具有计算值的Self
的新实例,但是,我不能从我的处理程序反序列化ArticleModel
,因为我必须反序列化为struct
,并且不能在那里调用new
函数.我还没有传递请求正文中的两个计算字段,这意味着它将返回一个json解析错误.
我怎么才能绕过这个问题呢?