mas_handlers/admin/v1/user_emails/
get.rs1use aide::{OperationIo, transform::TransformOperation};
7use axum::{Json, response::IntoResponse};
8use hyper::StatusCode;
9use mas_axum_utils::record_error;
10use ulid::Ulid;
11
12use crate::{
13 admin::{
14 call_context::CallContext,
15 model::UserEmail,
16 params::UlidPathParam,
17 response::{ErrorResponse, SingleResponse},
18 },
19 impl_from_error_for_route,
20};
21
22#[derive(Debug, thiserror::Error, OperationIo)]
23#[aide(output_with = "Json<ErrorResponse>")]
24pub enum RouteError {
25 #[error(transparent)]
26 Internal(Box<dyn std::error::Error + Send + Sync + 'static>),
27
28 #[error("User email ID {0} not found")]
29 NotFound(Ulid),
30}
31
32impl_from_error_for_route!(mas_storage::RepositoryError);
33
34impl IntoResponse for RouteError {
35 fn into_response(self) -> axum::response::Response {
36 let error = ErrorResponse::from_error(&self);
37 let sentry_event_id = record_error!(self, Self::Internal(_));
38 let status = match self {
39 Self::Internal(_) => StatusCode::INTERNAL_SERVER_ERROR,
40 Self::NotFound(_) => StatusCode::NOT_FOUND,
41 };
42 (status, sentry_event_id, Json(error)).into_response()
43 }
44}
45
46pub fn doc(operation: TransformOperation) -> TransformOperation {
47 operation
48 .id("getUserEmail")
49 .summary("Get a user email")
50 .tag("user-email")
51 .response_with::<200, Json<SingleResponse<UserEmail>>, _>(|t| {
52 let [sample, ..] = UserEmail::samples();
53 let response = SingleResponse::new_canonical(sample);
54 t.description("User email was found").example(response)
55 })
56 .response_with::<404, RouteError, _>(|t| {
57 let response = ErrorResponse::from_error(&RouteError::NotFound(Ulid::nil()));
58 t.description("User email was not found").example(response)
59 })
60}
61
62#[tracing::instrument(name = "handler.admin.v1.user_emails.get", skip_all)]
63pub async fn handler(
64 CallContext { mut repo, .. }: CallContext,
65 id: UlidPathParam,
66) -> Result<Json<SingleResponse<UserEmail>>, RouteError> {
67 let email = repo
68 .user_email()
69 .lookup(*id)
70 .await?
71 .ok_or(RouteError::NotFound(*id))?;
72
73 Ok(Json(SingleResponse::new_canonical(UserEmail::from(email))))
74}
75
76#[cfg(test)]
77mod tests {
78 use hyper::{Request, StatusCode};
79 use sqlx::PgPool;
80 use ulid::Ulid;
81
82 use crate::test_utils::{RequestBuilderExt, ResponseExt, TestState, setup};
83
84 #[sqlx::test(migrator = "mas_storage_pg::MIGRATOR")]
85 async fn test_get(pool: PgPool) {
86 setup();
87 let mut state = TestState::from_pool(pool).await.unwrap();
88 let token = state.token_with_scope("urn:mas:admin").await;
89 let mut rng = state.rng();
90
91 let mut repo = state.repository().await.unwrap();
93 let alice = repo
94 .user()
95 .add(&mut rng, &state.clock, "alice".to_owned())
96 .await
97 .unwrap();
98 let mas_data_model::UserEmail { id, .. } = repo
99 .user_email()
100 .add(
101 &mut rng,
102 &state.clock,
103 &alice,
104 "alice@example.com".to_owned(),
105 )
106 .await
107 .unwrap();
108
109 repo.save().await.unwrap();
110
111 let request = Request::get(format!("/api/admin/v1/user-emails/{id}"))
112 .bearer(&token)
113 .empty();
114 let response = state.request(request).await;
115 response.assert_status(StatusCode::OK);
116 let body: serde_json::Value = response.json();
117 assert_eq!(body["data"]["type"], "user-email");
118 insta::assert_json_snapshot!(body, @r###"
119 {
120 "data": {
121 "type": "user-email",
122 "id": "01FSHN9AG0AJ6AC5HQ9X6H4RP4",
123 "attributes": {
124 "created_at": "2022-01-16T14:40:00Z",
125 "user_id": "01FSHN9AG0MZAA6S4AF7CTV32E",
126 "email": "alice@example.com"
127 },
128 "links": {
129 "self": "/api/admin/v1/user-emails/01FSHN9AG0AJ6AC5HQ9X6H4RP4"
130 }
131 },
132 "links": {
133 "self": "/api/admin/v1/user-emails/01FSHN9AG0AJ6AC5HQ9X6H4RP4"
134 }
135 }
136 "###);
137 }
138
139 #[sqlx::test(migrator = "mas_storage_pg::MIGRATOR")]
140 async fn test_not_found(pool: PgPool) {
141 setup();
142 let mut state = TestState::from_pool(pool).await.unwrap();
143 let token = state.token_with_scope("urn:mas:admin").await;
144
145 let email_id = Ulid::nil();
146 let request = Request::get(format!("/api/admin/v1/user-emails/{email_id}"))
147 .bearer(&token)
148 .empty();
149 let response = state.request(request).await;
150 response.assert_status(StatusCode::NOT_FOUND);
151 }
152}