Skip to content

Commit

Permalink
update template
Browse files Browse the repository at this point in the history
  • Loading branch information
fankaiLiu committed Oct 20, 2023
1 parent b204716 commit eab5807
Show file tree
Hide file tree
Showing 6 changed files with 210 additions and 178 deletions.
10 changes: 4 additions & 6 deletions src/template/src/dtos/user.hbs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use salvo::prelude::ToSchema;
use salvo::prelude::{ToSchema, Extractible};
use serde::{Deserialize, Serialize};

#[derive(Deserialize, Debug, ToSchema, Default)]
Expand All @@ -13,17 +13,15 @@ pub struct UserLoginRequest {
pub password: String,
}

#[derive(Debug, Deserialize, ToSchema, Default)]
#[derive(Debug, Deserialize,Extractible,ToSchema, Default)]
#[salvo(extract(default_source(from = "body", format = "json")))]
pub struct UserUpdateRequest {
#[salvo(extract(source(from = "param")))]
pub id: String,
pub username: String,
pub password: String,
}

#[derive(Debug, Deserialize, ToSchema, Default)]
pub struct UserDeleteRequest {
pub id: String,
}

#[derive(Debug, Serialize, ToSchema, Default)]
pub struct UserResponse {
Expand Down
50 changes: 25 additions & 25 deletions src/template/src/routers/mod.hbs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ use salvo::{
prelude::{CatchPanic, Logger, OpenApi, SwaggerUi},
Router,
};

use self::{
demo::hello,
{{#if need_db_conn}}
Expand All @@ -27,35 +26,36 @@ pub mod user;
{{/if}}

pub fn router() -> Router {
{{#if is_web_site}}
{{#if need_db_conn}}
let mut no_auth_routers = vec![
Router::with_path("login").get(login_page),
Router::with_path("/api/login").post(post_login),
];

let mut need_auth_routers = vec![
Router::with_path("users")
.post(post_add_user)
.get(user_list_page),
Router::with_path("/api/users")
.get(get_users)
.put(post_update_user)
.push(Router::with_path("<id>").delete(delete_user)),
];
let router = Router::new()
.hoop(Logger::new())
.hoop(CatchPanic::new())
{{#if need_db_conn}}
.get(hello)
{{#if is_web_site}}
.push(Router::with_path("login").get(login_page).post(post_login))
{{else}}
.push(Router::with_path("login").post(post_login))
{{/if}}
.push(user_router().hoop(jwt_hoop()));
{{else}}
.get(hello);
{{/if}}
.append(&mut no_auth_routers)
.push(
Router::new()
.append(&mut need_auth_routers)
.hoop(jwt_hoop()),
);
{{/if}}
{{/if}}
let doc = OpenApi::new("salvo web api", "0.0.1").merge_router(&router);
router
.push(doc.into_router("/api-doc/openapi.json"))
.push(SwaggerUi::new("/api-doc/openapi.json").into_router("swagger-ui"))
}
{{#if need_db_conn}}
pub fn user_router() -> Router {
Router::with_path("user")
.post(post_add_user)
.put(post_update_user)
.delete(delete_user)
{{#if is_web_site}}
.get(user_list_page)
{{else}}
.get(get_users)
{{/if}}
}
{{/if}}
}
141 changes: 82 additions & 59 deletions src/template/src/routers/user.hbs
Original file line number Diff line number Diff line change
@@ -1,48 +1,24 @@
{{#if is_web_site}}
use askama::Template;
{{/if}}
{{#if is_web_site}}
use salvo::{
endpoint,
http::cookie::Cookie,
oapi::extract::{FormBody, JsonBody},
writing::{Redirect, Text},
Response,
};
use crate::{
app_error::AppResult,
app_response::{ErrRes, Res},
dtos::user::{
UserAddRequest, UserDeleteRequest, UserLoginRequest, UserResponse, UserUpdateRequest,
},
services::user,
};
{{else}}
use salvo::{
endpoint,
oapi::extract::{FormBody, JsonBody},
Response,
};
use crate::{
app_response::{ErrRes, Res},
dtos::user::{
UserAddRequest, UserDeleteRequest, UserLoginRequest, UserUpdateRequest,
},
services::user,
};
{{/if}}
{{#if is_web_site}}
#[derive(Template)]
#[template(path = "login.html")]
struct LoginTemplate {}

#[endpoint]
pub async fn login_page(res: &mut Response) -> AppResult<()> {
let cookies = res.cookies();
let cookie = cookies.get("jwt_token");
if let Some(cookie) = cookie {
let token = cookie.value().to_string();
if decode_token(&token) {
res.render(Redirect::other("/users"));
return Ok(());
} else {
}
}
let hello_tmpl = LoginTemplate {};
res.render(Text::Html(hello_tmpl.render().unwrap()));
Ok(())
}
{{/if}}

#[endpoint]
pub async fn post_add_user(req: JsonBody<UserAddRequest>, res: &mut Response) {
Expand All @@ -54,17 +30,18 @@ pub async fn post_add_user(req: JsonBody<UserAddRequest>, res: &mut Response) {
}

#[endpoint]
pub async fn post_update_user(req: JsonBody<UserUpdateRequest>, res: &mut Response) {
let result = user::update_user(req.0).await;
pub async fn put_update_user(req: &mut Request, res: &mut Response) {
let req: UserUpdateRequest = req.extract().await.unwrap();
let result = user::update_user(req).await;
match result {
Ok(data) => Res::with_data(data).into_response(res),
Err(e) => ErrRes::with_err(&e.to_string()).into_response(res),
}
}

#[endpoint]
pub async fn delete_user(req: JsonBody<UserDeleteRequest>, res: &mut Response) {
let result = user::delete_user(req.0).await;
pub async fn delete_user(id: PathParam<String>, res: &mut Response) {
let result = user::delete_user(id.0).await;
match result {
Ok(_) => Res::with_data(()).into_response(res),
Err(e) => ErrRes::with_err(&e.to_string()).into_response(res),
Expand All @@ -79,26 +56,11 @@ pub async fn get_users(res: &mut Response) {
Err(e) => ErrRes::with_err(&e.to_string()).into_response(res),
}
}
{{#if is_web_site}}

#[derive(Template)]
#[template(path = "user_list_page.html")]
pub struct UserListPageTemplate {
users: Vec<UserResponse>,
}

#[endpoint]
pub async fn user_list_page(res: &mut Response) -> AppResult<()> {
let users = user::users().await?;
let hello_tmpl = UserListPageTemplate { users };

res.render(Text::Html(hello_tmpl.render().unwrap()));
Ok(())
}

#[endpoint]
pub async fn post_login(req: FormBody<UserLoginRequest>, res: &mut Response) {
let result = user::login(req.0).await;
pub async fn post_login(req: JsonBody<UserLoginRequest>, res: &mut Response) {
let result: Result<crate::dtos::user::UserLoginResponse, crate::app_error::AppError> =
user::login(req.0).await;
match result {
Ok(data) => {
let jwt_token = data.token.clone();
Expand All @@ -107,15 +69,76 @@ pub async fn post_login(req: FormBody<UserLoginRequest>, res: &mut Response) {
.http_only(true)
.finish();
res.add_cookie(cookie);
res.render(Redirect::other("/user"));
}
Err(e) => ErrRes::with_err(&e.to_string()).into_response(res),
}
}
#[derive(Template)]
#[template(path = "user_list_page.html")]
pub struct UserListPageTemplate {}

#[derive(Template)]
#[template(path = "user_list.html")]
pub struct UserListTemplate {}

#[endpoint]
pub async fn user_list_page(req: &mut Request, res: &mut Response) -> AppResult<()> {
let is_fragment = req.headers().get("X-Fragment-Header");
match is_fragment {
Some(_) => {
let hello_tmpl = UserListTemplate {};
res.render(Text::Html(hello_tmpl.render().unwrap()));
}
None => {
let hello_tmpl = UserListPageTemplate {};
res.render(Text::Html(hello_tmpl.render().unwrap()));
}
}
Ok(())
}
{{else}}
use salvo::{
endpoint,
oapi::extract::{FormBody, JsonBody},
Response,
};
use crate::{
app_response::{ErrRes, Res},
dtos::user::{
UserAddRequest, UserDeleteRequest, UserLoginRequest, UserUpdateRequest,
},
services::user,
};
#[endpoint]
pub async fn post_login(req: FormBody<UserLoginRequest>, res: &mut Response) {
let result = user::login(req.0).await;
pub async fn post_add_user(req: JsonBody<UserAddRequest>, res: &mut Response) {
let result = user::add_user(req.0).await;
match result {
Ok(data) => Res::with_data(data).into_response(res),
Err(e) => ErrRes::with_err(&e.to_string()).into_response(res),
}
}

#[endpoint]
pub async fn post_update_user(req: JsonBody<UserUpdateRequest>, res: &mut Response) {
let result = user::update_user(req.0).await;
match result {
Ok(data) => Res::with_data(data).into_response(res),
Err(e) => ErrRes::with_err(&e.to_string()).into_response(res),
}
}

#[endpoint]
pub async fn delete_user(req: JsonBody<UserDeleteRequest>, res: &mut Response) {
let result = user::delete_user(req.0).await;
match result {
Ok(_) => Res::with_data(()).into_response(res),
Err(e) => ErrRes::with_err(&e.to_string()).into_response(res),
}
}

#[endpoint]
pub async fn get_users(res: &mut Response) {
let result = user::users().await;
match result {
Ok(data) => Res::with_data(data).into_response(res),
Err(e) => ErrRes::with_err(&e.to_string()).into_response(res),
Expand Down
2 changes: 1 addition & 1 deletion src/template/templates/login.hbs
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@
},
});
this.userList = await userListResponse.text();
history.pushState(null, '', '/user');
//history.pushState(null, '', '/user');
} catch (error) {
Swal.fire({
title: "Error!",
Expand Down
Loading

0 comments on commit eab5807

Please sign in to comment.