I have a model here:
#[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
}
that in my api handlers, I try to convert the body of a request into like so:
#[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()),
}
}
Except, I don't want to have to pass the fields read_time_in_min
and word_count
up in the body of the request. I'm trying to have them calculated based on what the text
field says. These functions take &text
as an input, and output an i32
.
I can't figure out how to lay this out. I've thought to create an ArticleModel
impl
block that has an associated new
function that takes in the required params, and then outputs a new instance of Self
that has the calculated values, except, then, I can't deserialize ArticleModel
from my handlers, since I have to deserialize into a struct
and can't call a new
function there. I also won't have passed up the 2 calculated fields in the body of the request, meaning it'll return a json parsing error.
How do I get around this?