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
78
79
80
81
82
|
use askama::Template;
use axum::{
extract::{Query, State},
http::Uri,
response::{Html, IntoResponse, Response},
routing::get,
};
use serde::Deserialize;
use uuid::Uuid;
use crate::{
api::users::UserSchema,
state::{self, AppState},
};
use self::error::Error;
pub mod error;
pub fn router() -> axum::Router<state::AppState> {
axum::Router::new()
.route("/search", get(search))
.route("/healthcheck", get(healthcheck))
.fallback(fallback)
}
pub async fn healthcheck() -> Html<&'static str> {
Html("OK")
}
pub async fn fallback(uri: Uri) -> Error {
self::error::Error::RouteNotFound(uri)
}
#[derive(Template)]
#[template(path = "users.html")]
struct UsersTemplate {
users: Vec<UserSchema>,
}
#[derive(Debug, Deserialize)]
struct Params {
#[serde(default, deserialize_with = "crate::utils::empty_string_as_none")]
name: Option<String>,
}
async fn search(
State(state): State<AppState>,
Query(params): Query<Params>,
) -> Result<impl IntoResponse, Error> {
let users = if let Some(name) = params.name {
sqlx::query_as!(
UserSchema,
"SELECT * FROM user_ WHERE name = $1 LIMIT 100",
name
)
.fetch_all(&state.pool)
.await?
} else {
sqlx::query_as!(UserSchema, "SELECT * FROM user_ LIMIT 100",)
.fetch_all(&state.pool)
.await?
};
let template = UsersTemplate { users };
Ok(HtmlTemplate(template))
}
struct HtmlTemplate<T>(T);
impl<T> IntoResponse for HtmlTemplate<T>
where
T: Template,
{
fn into_response(self) -> Response {
self.0
.render()
.map(Html)
.map_err(Into::<Error>::into)
.into_response()
}
}
|