-
-
Notifications
You must be signed in to change notification settings - Fork 526
/
Copy pathlib.rs
211 lines (174 loc) Β· 5.65 KB
/
lib.rs
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
mod flash;
use axum::{
extract::{Form, Path, Query, State},
http::StatusCode,
response::Html,
routing::{get, get_service, post},
Router,
};
use axum_example_service::{
sea_orm::{Database, DatabaseConnection},
Mutation as MutationCore, Query as QueryCore,
};
use entity::post;
use flash::{get_flash_cookie, post_response, PostResponse};
use migration::{Migrator, MigratorTrait};
use serde::{Deserialize, Serialize};
use std::env;
use tera::Tera;
use tower_cookies::{CookieManagerLayer, Cookies};
use tower_http::services::ServeDir;
#[tokio::main]
async fn start() -> anyhow::Result<()> {
env::set_var("RUST_LOG", "debug");
tracing_subscriber::fmt::init();
dotenvy::dotenv().ok();
let db_url = env::var("DATABASE_URL").expect("DATABASE_URL is not set in .env file");
let host = env::var("HOST").expect("HOST is not set in .env file");
let port = env::var("PORT").expect("PORT is not set in .env file");
let server_url = format!("{host}:{port}");
let conn = Database::connect(db_url)
.await
.expect("Database connection failed");
Migrator::up(&conn, None).await.unwrap();
let templates = Tera::new(concat!(env!("CARGO_MANIFEST_DIR"), "/templates/**/*"))
.expect("Tera initialization failed");
let state = AppState { templates, conn };
let app = Router::new()
.route("/", get(list_posts).post(create_post))
.route("/:id", get(edit_post).post(update_post))
.route("/new", get(new_post))
.route("/delete/:id", post(delete_post))
.nest_service(
"/static",
get_service(ServeDir::new(concat!(
env!("CARGO_MANIFEST_DIR"),
"/static"
)))
.handle_error(|error| async move {
(
StatusCode::INTERNAL_SERVER_ERROR,
format!("Unhandled internal error: {error}"),
)
}),
)
.layer(CookieManagerLayer::new())
.with_state(state);
let listener = tokio::net::TcpListener::bind(&server_url).await.unwrap();
axum::serve(listener, app).await?;
Ok(())
}
#[derive(Clone)]
struct AppState {
templates: Tera,
conn: DatabaseConnection,
}
#[derive(Deserialize)]
struct Params {
page: Option<u64>,
posts_per_page: Option<u64>,
}
#[derive(Deserialize, Serialize, Debug, Clone)]
struct FlashData {
kind: String,
message: String,
}
async fn list_posts(
state: State<AppState>,
Query(params): Query<Params>,
cookies: Cookies,
) -> Result<Html<String>, (StatusCode, &'static str)> {
let page = params.page.unwrap_or(1);
let posts_per_page = params.posts_per_page.unwrap_or(5);
let (posts, num_pages) = QueryCore::find_posts_in_page(&state.conn, page, posts_per_page)
.await
.expect("Cannot find posts in page");
let mut ctx = tera::Context::new();
ctx.insert("posts", &posts);
ctx.insert("page", &page);
ctx.insert("posts_per_page", &posts_per_page);
ctx.insert("num_pages", &num_pages);
if let Some(value) = get_flash_cookie::<FlashData>(&cookies) {
ctx.insert("flash", &value);
}
let body = state
.templates
.render("index.html.tera", &ctx)
.map_err(|_| (StatusCode::INTERNAL_SERVER_ERROR, "Template error"))?;
Ok(Html(body))
}
async fn new_post(state: State<AppState>) -> Result<Html<String>, (StatusCode, &'static str)> {
let ctx = tera::Context::new();
let body = state
.templates
.render("new.html.tera", &ctx)
.map_err(|_| (StatusCode::INTERNAL_SERVER_ERROR, "Template error"))?;
Ok(Html(body))
}
async fn create_post(
state: State<AppState>,
mut cookies: Cookies,
form: Form<post::Model>,
) -> Result<PostResponse, (StatusCode, &'static str)> {
let form = form.0;
MutationCore::create_post(&state.conn, form)
.await
.expect("could not insert post");
let data = FlashData {
kind: "success".to_owned(),
message: "Post successfully added".to_owned(),
};
Ok(post_response(&mut cookies, data))
}
async fn edit_post(
state: State<AppState>,
Path(id): Path<i32>,
) -> Result<Html<String>, (StatusCode, &'static str)> {
let post: post::Model = QueryCore::find_post_by_id(&state.conn, id)
.await
.expect("could not find post")
.unwrap_or_else(|| panic!("could not find post with id {id}"));
let mut ctx = tera::Context::new();
ctx.insert("post", &post);
let body = state
.templates
.render("edit.html.tera", &ctx)
.map_err(|_| (StatusCode::INTERNAL_SERVER_ERROR, "Template error"))?;
Ok(Html(body))
}
async fn update_post(
state: State<AppState>,
Path(id): Path<i32>,
mut cookies: Cookies,
form: Form<post::Model>,
) -> Result<PostResponse, (StatusCode, String)> {
let form = form.0;
MutationCore::update_post_by_id(&state.conn, id, form)
.await
.expect("could not edit post");
let data = FlashData {
kind: "success".to_owned(),
message: "Post successfully updated".to_owned(),
};
Ok(post_response(&mut cookies, data))
}
async fn delete_post(
state: State<AppState>,
Path(id): Path<i32>,
mut cookies: Cookies,
) -> Result<PostResponse, (StatusCode, &'static str)> {
MutationCore::delete_post(&state.conn, id)
.await
.expect("could not delete post");
let data = FlashData {
kind: "success".to_owned(),
message: "Post successfully deleted".to_owned(),
};
Ok(post_response(&mut cookies, data))
}
pub fn main() {
let result = start();
if let Some(err) = result.err() {
println!("Error: {err}");
}
}