summaryrefslogtreecommitdiffstats
path: root/src/server/routes/users/get_user.rs
blob: d86cc26d9f7ea9435e5108b0fd2488a139aa89de (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
use activitypub_federation::{
    axum::json::FederationJson, config::Data, protocol::context::WithContext, traits::Object,
};
use axum::{debug_handler, extract::Path, http::StatusCode, response::IntoResponse};

use crate::{error::AppError, state::AppHandle};

#[debug_handler]
pub async fn http_get_user(
    Path(name): Path<String>,
    data: Data<AppHandle>,
) -> Result<impl IntoResponse, AppError> {
    if let Some(a) = read_user(&name, &data).await {
        let json_user = a.into_json(&data).await?;
        Ok((
            StatusCode::OK,
            FederationJson(WithContext::new_default(json_user)),
        )
            .into_response())
    } else {
        Ok((StatusCode::NOT_FOUND, "").into_response())
    }
}

pub async fn read_user(name: &str, data: &Data<AppHandle>) -> Option<crate::entity::user::User> {
    let read = data.users.read().await;
    read.iter()
        .find(|value| value.username.eq(&name))
        .map(ToOwned::to_owned)
}

#[cfg(test)]
mod tests {
    use axum::{
        body::Body,
        http::{Request, StatusCode},
    };
    use tower::ServiceExt;

    use crate::{server, state::AppState};

    #[tokio::test]
    async fn get_user() {
        let state = AppState::new().await.unwrap();
        let app = server::router(state);

        let response = app
            .oneshot(
                Request::builder()
                    .uri("/users/sellershut")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::OK);
    }

    #[tokio::test]
    async fn get_user_not_found() {
        let state = AppState::new().await.unwrap();
        let app = server::router(state);

        let response = app
            .oneshot(
                Request::builder()
                    .uri("/users/selut")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::NOT_FOUND);
    }
}