summaryrefslogtreecommitdiff
path: root/src/conversation/handlers/send/mod.rs
blob: ff6365262843265b2ee7aa38eec2cacb73342325 (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
use axum::{
    extract::{Json, Path, State},
    http::StatusCode,
    response::{self, IntoResponse},
};

use crate::{
    clock::RequestedAt,
    conversation::handlers::PathInfo,
    error::{Internal, NotFound},
    message::{
        Body, Message,
        app::{Messages, SendError},
    },
    token::extract::Identity,
};

#[cfg(test)]
mod test;

pub async fn handler(
    State(messages): State<Messages>,
    Path(conversation): Path<PathInfo>,
    RequestedAt(sent_at): RequestedAt,
    identity: Identity,
    Json(request): Json<Request>,
) -> Result<Response, Error> {
    let message = messages
        .send(&conversation, &identity.login, &sent_at, &request.body)
        .await?;

    Ok(Response(message))
}

#[derive(serde::Deserialize)]
pub struct Request {
    pub body: Body,
}

#[derive(Debug)]
pub struct Response(pub Message);

impl IntoResponse for Response {
    fn into_response(self) -> response::Response {
        let Self(message) = self;
        (StatusCode::ACCEPTED, Json(message)).into_response()
    }
}

#[derive(Debug, thiserror::Error)]
#[error(transparent)]
pub struct Error(#[from] pub SendError);

impl IntoResponse for Error {
    fn into_response(self) -> response::Response {
        let Self(error) = self;
        match error {
            SendError::ConversationNotFound(_) | SendError::ConversationDeleted(_) => {
                NotFound(error).into_response()
            }
            SendError::SenderNotFound(_)
            | SendError::SenderDeleted(_)
            | SendError::Name(_)
            | SendError::Database(_) => Internal::from(error).into_response(),
        }
    }
}