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

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

#[cfg(test)]
mod test;

pub async fn handler(
    State(app): State<App>,
    Path(channel): Path<PathInfo>,
    RequestedAt(sent_at): RequestedAt,
    identity: Identity,
    Json(request): Json<Request>,
) -> Result<Response, Error> {
    let message = app
        .messages()
        .send(&channel, &identity.user, &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::ChannelNotFound(_) => NotFound(error).into_response(),
            SendError::Name(_) | SendError::Database(_) => Internal::from(error).into_response(),
        }
    }
}