summaryrefslogtreecommitdiff
path: root/src/message/handlers/delete/mod.rs
blob: c09a7522edb1f854173b09274f6bdcfe0f388fdf (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::{
    clock::RequestedAt,
    error::{Internal, NotFound},
    message::{
        self,
        app::{DeleteError, Messages},
    },
    token::extract::Identity,
};

#[cfg(test)]
mod test;

pub async fn handler(
    State(messages): State<Messages>,
    Path(message): Path<message::Id>,
    RequestedAt(deleted_at): RequestedAt,
    identity: Identity,
) -> Result<Response, Error> {
    messages
        .delete(&identity.login, &message, &deleted_at)
        .await?;

    Ok(Response { id: message })
}

#[derive(Debug, serde::Serialize)]
pub struct Response {
    pub id: message::Id,
}

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

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

impl IntoResponse for Error {
    fn into_response(self) -> response::Response {
        let Self(error) = self;
        match error {
            DeleteError::NotSender(_) => (StatusCode::FORBIDDEN, error.to_string()).into_response(),
            DeleteError::MessageNotFound(_) | DeleteError::Deleted(_) => {
                NotFound(error).into_response()
            }
            DeleteError::Database(_) | DeleteError::Name(_) => {
                Internal::from(error).into_response()
            }
        }
    }
}