1
\$\begingroup\$

I'm currently learning rust and need a rocket file upload enpoint for a project.

This is what i currently have:

It needs to get the file, convert it and add a entry with the file name and timestamp to a database.

#[post("/upload?<auth>", data = "<file>")]
pub async fn upload(
                config: &State<Config>,
                db: &State<Db>, 
                mut file: Form<TempFile<'_>>,
                auth: Option<String>
            ) -> Status {

    if !is_valid_token(auth, &config) {
        return Status::Forbidden 
    }

    let filename = utils::get_random_string(20);
    let temp_path = Path::new("/tmp").join(&filename);
    let save_path = Path::new(&config.image_dir).join(&filename); 

    if let Err(_) = file.copy_to(&temp_path).await {
        return Status::InternalServerError
    };

    let image_res = utils::check_and_convert_image(&temp_path, &save_path);
    if let Err(_) = image_res {
        if let Err(_) = fs::remove_file(temp_path) {
            return Status::InternalServerError
        }

        return Status::BadRequest
    }

    if let Err(_) = fs::remove_file(temp_path) {
        return Status::InternalServerError
    }

    let timestamp = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap().as_secs();
    let db_entry = Entry {
        timestamp,
        filename,
    };

    if let Err(_) = db.create_entry(db_entry) {
        return Status::InternalServerError
    };

    return Status::Ok
}

In the rocket docs it says that using Status as a return type is not recommended (https://rocket.rs/v0.5-rc/guide/responses/#responses) and checking if every function fails seems like bad practise.

Is there a better way of doing this?

\$\endgroup\$

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Browse other questions tagged or ask your own question.