|
1 | 1 | use askama::Template; |
2 | 2 | use askama_web::WebTemplate; |
3 | 3 | use axum::extract::State; |
4 | | -use axum::response::{IntoResponse, Response}; |
5 | 4 | use snafu::prelude::*; |
6 | 5 |
|
7 | 6 | // TUTORIAL: https://github.com/SeaQL/sea-orm/blob/master/examples/axum_example/ |
8 | 7 | use crate::database::category::CategoryOperator; |
9 | 8 | use crate::extractors::user::User; |
10 | 9 | use crate::state::{AppState, AppStateContext, error::*}; |
11 | 10 |
|
12 | | -use std::collections::HashMap; |
13 | | - |
14 | 11 | #[derive(Template, WebTemplate)] |
15 | 12 | #[template(path = "index.html")] |
16 | 13 | pub struct IndexTemplate { |
17 | 14 | /// Global application state (errors/warnings) |
18 | 15 | pub state: AppStateContext, |
19 | | - /// TODO: Submitted values in a POST request |
20 | | - /// |
21 | | - /// This happens when the request was rejected by the handler, but still |
22 | | - /// wants to repopulate form data from submitted values. |
23 | | - pub post: HashMap<String, String>, |
24 | 16 | /// Logged-in user. |
25 | 17 | pub user: Option<User>, |
26 | 18 | /// Categories |
27 | 19 | pub categories: Vec<String>, |
28 | 20 | } |
29 | 21 |
|
| 22 | +impl IndexTemplate { |
| 23 | + pub async fn new(app_state: AppState, user: Option<User>) -> Result<Self, AppStateError> { |
| 24 | + let categories: Vec<String> = CategoryOperator::new(app_state.clone(), user.clone()) |
| 25 | + .list() |
| 26 | + .await |
| 27 | + .context(CategorySnafu)? |
| 28 | + .into_iter() |
| 29 | + .map(|x| x.name) |
| 30 | + .collect(); |
| 31 | + |
| 32 | + Ok(IndexTemplate { |
| 33 | + state: app_state.context().await?, |
| 34 | + user, |
| 35 | + categories, |
| 36 | + }) |
| 37 | + } |
| 38 | +} |
| 39 | + |
30 | 40 | pub async fn index( |
31 | 41 | State(app_state): State<AppState>, |
32 | 42 | user: Option<User>, |
33 | | -) -> Result<Response, AppStateError> { |
34 | | - let app_state_context = app_state.context().await?; |
35 | | - |
36 | | - let categories: Vec<String> = CategoryOperator::new(app_state.clone(), user.clone()) |
37 | | - .list() |
38 | | - .await |
39 | | - .context(CategorySnafu)? |
40 | | - .into_iter() |
41 | | - .map(|x| x.name) |
42 | | - .collect(); |
43 | | - |
44 | | - Ok(IndexTemplate { |
45 | | - state: app_state_context, |
46 | | - post: HashMap::new(), |
47 | | - user, |
48 | | - categories, |
49 | | - } |
50 | | - .into_response()) |
| 43 | +) -> Result<IndexTemplate, AppStateError> { |
| 44 | + IndexTemplate::new(app_state, user).await |
51 | 45 | } |
0 commit comments