Add Question Function in Rust Web Development

The add_question function is a crucial component in a Rust-based web application, responsible for adding new questions to a database. This function is implemented using the Warp web framework and involves several steps to ensure data integrity and security, such as profanity checking and database interaction.

Overview

The add_question function is designed to handle the addition of new questions to a database. It accepts a NewQuestion object, which includes the title, content, and tags of the question. The function returns a Result type, indicating the success or failure of the operation. The process involves checking the title and content for profanity and updating them if necessary before storing them.

Implementation Details

Initial Route Handler

The initial implementation of the add_question route handler is straightforward. It directly inserts the question into the store and returns a success message if the operation is successful.

Listing 4.31 Adding a route handler for adding a question to the store

async fn add_question(
   store: Store, 
   question: Question
) -> Result<impl warp::Reply, warp::Rejection> { 
   store.questions.write().await.insert(question.id.clone(), question);

   Ok(warp::reply::with_status(
       "Question added",
       StatusCode::OK,
   ))
}

Updated Route Handler with Database Interaction

The route handler is updated to interact with a database using the sqlx library. This version of the function wraps the database operation and returns appropriate HTTP status codes.

Listing 7.18 Updating the add_question route handler in routes/question.rs

use crate::types::question::NewQuestion;
...
 
pub async fn add_question(
    store: Store,
    new_question: NewQuestion,
) -> Result<impl warp::Reply, warp::Rejection> {
    if let Err(e) = store.add_question(new_question).await {
        return Err(warp::reject::custom(Error::DatabaseQueryError(e)));
    }
 
    Ok(warp::reply::with_status("Question added", StatusCode::OK))
}

Profanity Check Integration

In the latest iteration, the add_question function incorporates a profanity check for both the title and content of the question. This ensures that any inappropriate language is filtered out before the question is stored.

Listing 8.19 The updated add_question route handler

use crate::profanity::check_profanity;

pub async fn add_question(
    store: Store,
    new_question: NewQuestion,
) -> Result<impl warp::Reply, warp::Rejection> {
    let title = match check_profanity(new_question.title).await {
        Ok(res) => res,
        Err(e) => return Err(warp::reject::custom(e)),
    };

    let content = match check_profanity(new_question.content).await {
        Ok(res) => res,
        Err(e) => return Err(warp::reject::custom(e)),
    };

    let question = NewQuestion {
        title,
        content,
        tags: new_question.tags,
    };
    match store.add_question(question).await {
        Ok(_) => Ok(warp::reply::with_status(
            "Question added", 
            StatusCode::OK
        )),
        Err(e) => Err(warp::reject::custom(e)),
    }
}

Database Function in Store

The add_question function in the store.rs file is responsible for executing the SQL query to insert the new question into the database. It uses the sqlx library to bind the question's attributes and handle the database response.

Listing 7.17 Adding the add_question function to store.rs

use crate::types::question::NewQuestion;

pub async fn add_question(
   &self, 
   new_question: NewQuestion
) -> Result<Question, sqlx::Error> {
   match sqlx::query(
       "INSERT INTO questions (title, content, tags) 
       VALUES ($1, $2, $3)"
   )
   .bind(new_question.title)
   .bind(new_question.content)
   .bind(new_question.tags)
   .map(|row: PgRow| Question {
        id: QuestionId(row.get("id")),
        title: row.get("title"),
        content: row.get("content"),
        tags: row.get("tags"),
    })
    .fetch_one(&self.connection)
    .await 
    {
         Ok(question) => Ok(question),
         Err(e) => Err(e),
     }
}

In summary, the add_question function is a well-structured component that ensures new questions are added to the database securely and appropriately, with checks for profanity and proper error handling.

FAQ (Frequently asked questions)

What happens if there is an error when adding a question in the updated add_question function?

What additional checks does the add_question function perform before storing a question?