8 releases

0.1.7 May 21, 2024
0.1.6 May 9, 2024
0.1.4 Mar 22, 2024

#1691 in Database interfaces

Download history 11/week @ 2024-05-25 2/week @ 2024-06-08 1/week @ 2024-06-15

655 downloads per month

MIT license

63KB
206 lines

Axum Responses

A Simple way to use Axum responses and results

Example


// Asume we have a mongodb database connection and a user model
// A simple service that returns a generic or an error

use bson::
use axum::Json;
use serde_json::{Value, to_value};
use axum_responses::{AxumResult, HttpResponse, AxumResponse};

#[derive(Debug, Serialize, Deserialize)]
struct LoginData {
    email: String,
    password: String
}

async fn get_user_by_id(filter: doc) -> AxumResult<User> {

    let user = User::find_by_id(filter).await
        .map_err(|_| HttpResponse::INTERNAL_SERVER_ERROR)?
    ;

    Ok(user)
}

// And then we can use it in a simple login controller like this

async fn login_controller(Json(body): Json<LoginData>) -> AxumResponse {

    let filter = doc! { "email": body.email };
    let user = get_user_by_id(filter).await?;

    if user.password != body.password {
        return Err(HttpResponse::UNAUTHORIZED)
    }

    Ok(HttpResponse::JSON(
        200, "OK", "user", user.to_value().unwrap_or(Value::Null))
    )
}

Dependencies

~10–19MB
~278K SLoC