Add Answer Route Handler in Rust Web Development

The add_answer function is a crucial component in a Rust web application that allows users to add answers to questions stored in a database. This function is implemented using the Warp web framework and involves several steps to ensure data integrity and security.

Overview

The add_answer function is designed to handle HTTP POST requests to add a new answer to a question. It takes a NewAnswer object as input, which includes the content of the answer and the associated question_id. The function returns a Result indicating whether the operation was successful or if it encountered an error.

Implementation Details

Route Handler Setup

The route handler for adding an answer is set up in the main function of the application. The following listing shows how the route is defined and integrated into the application's routing logic:

Listing 4.39 Adding a route handler to add an answer via a url-form body

#[tokio::main]
async fn main() {
    let store = Store::new();
    let store_filter = warp::any().map(move || store.clone());

    let add_answer = warp::post()
        .and(warp::path("answers"))
        .and(warp::path::end())
        .and(store_filter.clone())
        .and(warp::body::form())
        .and_then(add_answer);

    let routes = get_questions
        .or(update_question)
        .or(add_question)
        .or(add_answer)
        .or(delete_question)
        .with(cors)
        .recover(return_error);

    warp::serve(routes)
        .run(([127, 0, 0, 1], 3030))
        .await;
}

In this setup, the warp::body::form filter is used to parse the incoming form data into a HashMap<String, String>, which is then passed to the add_answer function.

Adding an Answer

The add_answer function processes the incoming data, checks for profanity, and stores the answer in the database. The following listing shows the implementation of the add_answer function:

Listing 8.21 Updated add_answer route handler in src/routes/answer.rs

use std::collections::HashMap;
use warp::http::StatusCode;

use crate::store::Store;
use crate::types::answer::NewAnswer;
use crate::profanity::check_profanity;

pub async fn add_answer(
    store: Store,
    new_answer: NewAnswer,
) -> Result<impl warp::Reply, warp::Rejection> {
    let content = match 
        check_profanity(params.get("content").unwrap().to_string()).await {
            Ok(res) => res,
            Err(e) => return Err(warp::reject::custom(e)),
        };

    let answer = NewAnswer {
        content,
        question_id: new_answer.question_id,
    };

    match store.add_answer(answer).await {
        Ok(_) => Ok(warp::reply::with_status(
            "Answer added", 
            StatusCode::OK
        )),
        Err(e) => Err(warp::reject::custom(e)),
    }
}

Profanity Check

Before storing the answer, the content is checked for profanity using the check_profanity function. If any profane words are found, they are censored before the answer is stored.

Storing the Answer

The add_answer function in the Store struct is responsible for inserting the new answer into the database. The following listing shows how this is done:

Listing 7.25 Extending the store with an add_answer function

// ch_07/src/store.rs

use crate::types::{
    answer::{Answer, NewAnswer, AnswerId},
    question::{Question, QuestionId, NewQuestion},
};

pub async fn add_answer(
    &self, 
    new_answer: NewAnswer
) -> Result<Answer, Error> {
    match sqlx::query(
        "INSERT INTO answers (content, question_id) VALUES ($1, $2)"
    )
    .bind(new_answer.content)
    .bind(new_answer.question_id.0)
    .map(|row: PgRow| Answer {
           id: AnswerId(row.get("id")),
           content: row.get("content"),
           question_id: QuestionId(row.get("question_id")),
    })
    .fetch_one(&self.connection)
    .await {
        Ok(answer) => Ok(answer),
        Err(e) => {
           tracing::event!(tracing::Level::ERROR, "{:?}", e);
            Err(Error::DatabaseQueryError(e))
        },
    }
}

This function uses SQLx to execute an SQL query that inserts the new answer into the database, binding the content and question ID to the query parameters. If successful, it returns the newly created Answer object; otherwise, it logs the error and returns a DatabaseQueryError.

FAQ (Frequently asked questions)

What additional step is involved in the add_answer function before storing an answer?