Skip to content

Commit

Permalink
wip
Browse files Browse the repository at this point in the history
  • Loading branch information
chrislearn committed Jan 17, 2025
1 parent 0db7a23 commit 2f65bbb
Show file tree
Hide file tree
Showing 8 changed files with 66 additions and 53 deletions.
12 changes: 8 additions & 4 deletions templates/classic/_base/src/config/mod.rs.liquid
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
use once_cell::sync::Lazy;
use serde::Deserialize;
use std::sync::OnceLock;
use std::{fs::File, io::Read, path::Path};

use serde::Deserialize;
use salvo::http::HeaderValue;

use crate::config;


pub static CONFIG: OnceLock<ServerConfig> = OnceLock::new();

Expand Down Expand Up @@ -89,8 +93,8 @@ impl CertKey {
}
}
fn get_cert_key() -> CertKey {
let cert = get_string(&CFG.cert.cert);
let key = get_string(&CFG.cert.key);
let cert = get_string(&config().cert.cert);
let key = get_string(&config()cert.key);
CertKey::new(cert, key)
}

Expand Down
23 changes: 19 additions & 4 deletions templates/classic/_base/src/error.rs.liquid
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,18 @@ use salvo::http::ParseError;
{% if db_type == "mongodb" %}
use mongodb::bson::document::ValueAccessError as MongoBsonAccessError;
use mongodb::bson::oid::Error as MongoBsonOidError;
use mongodb::error::Error as MongoDbError;
use mongodb::error::Error as MongoDbErroror;
{% endif %}
use thiserror::Error;

#[derive(Error, Debug)]
pub enum AppError {
#[error("public: `{0}`")]
Public(String),
#[error("internal: `{0}`")]
Internal(String),
#[error("salvo internal error: `{0}`")]
Salvo(#[from] ::salvo::Error),
#[error("error:`{0}`")]
AnyHow(#[from] anyhow::Error),
#[error("http::ParseError:`{0}`")]
Expand All @@ -17,8 +23,8 @@ pub enum AppError {
SqlxError(#[from] sqlx::Error),
{% endif %}
{% if db_lib == "seaorm" %}
#[error("seaorm::DbErr:Error:`{0}`")]
DbErr(#[from] seaorm::DbErr),
#[error("seaorm::DbError:Error:`{0}`")]
DbError(#[from] seaorm::DbError),
{% endif %}
{% if db_lib == "diesel" %}
#[error("diesel::result::Error:`{0}`")]
Expand All @@ -30,7 +36,7 @@ pub enum AppError {
{% endif %}
{% if db_type == "mongodb" %}
#[error("mongodb::error::Error:`{0}`")]
MongoDbErr(#[from] MongoDbError),
MongoDbError(#[from] MongoDbErroror),
#[error("mongodb::bson::document::ValueAccessError:`{0}`")]
MongoBsonAccessError(#[from] MongoBsonAccessError),
#[error("mongodb::bson::oid::Error`{0}`")]
Expand All @@ -39,6 +45,15 @@ pub enum AppError {
#[error("ValidationError:`{0}`")]
ValidationError(#[from] validator::ValidationErrors),
}
impl AppError {
pub fn public<S: Into<String>>(msg: S) -> Self {
Self::Public(msg.into())
}

pub fn internal<S: Into<String>>(msg: S) -> Self {
Self::Internal(msg.into())
}
}

impl EndpointOutRegister for AppError {
fn register(_components: &mut salvo::oapi::Components, operation: &mut salvo::oapi::Operation) {
Expand Down
11 changes: 11 additions & 0 deletions templates/classic/_base/src/main.rs.liquid
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use std::sync::Arc;

use crate::db::init_db_conn;
use tokio::signal;
Expand Down Expand Up @@ -26,6 +27,16 @@ mod error;
pub use error::AppError;

pub type AppResult<T> = Result<T, AppError>;
pub type JsonResult<T> = Result<Json<T>, AppError>;

pub fn json_ok<T>(data: T) -> JsonResult<T> {
Ok(Json(data))
}
#[derive(Serialize, ToSchema, Clone, Copy, Debug)]
pub struct Empty {}
pub fn empty_ok() -> JsonResult<Empty> {
Ok(Json(Empty {}))
}

use config::ServerConfig;
pub fn config() -> &'static ServerConfig {
Expand Down
5 changes: 3 additions & 2 deletions templates/classic/_base/src/routers/demo.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@

use askama::Template;
use salvo::prelude::*;

use crate::AppResult;

#[handle]
pub async fn hello(req: &mut Request, res: &mut Response)->AppResult<Text>{
#[handler]
pub async fn hello(req: &mut Request, res: &mut Response) -> AppResult<Text>{
#[derive(Template)]
#[template(path = "hello.html")]
struct HelloTemplate<'a> {
Expand Down
21 changes: 9 additions & 12 deletions templates/classic/_base/src/routers/user.rs.liquid
Original file line number Diff line number Diff line change
@@ -1,24 +1,21 @@
use crate::{JsonResult, AppResult, json_ok, json_empty};
use crate::{
dtos::user::{
UserAddRequest, UserLoginRequest, UserLoginResponse, UserResponse, UserUpdateRequest,
},
middleware::jwt::decode_token,
services::user,
};
use validator::Validate;
use serde::{Deserialize, Serialize};

use askama::Template;
use salvo::prelude::*;
use validator::Validate;

use crate::hoops::jwt::decode_token;
use crate::{empty_ok, json_ok, AppResult, JsonResult};

#[derive(Template)]
#[template(path = "user_list_page.html")]
#[template(path = "views/user_list_page.html")]
pub struct UserListPageTemplate {}

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

#[handle]
#[handler]
pub async fn list_page(req: &mut Request, res: &mut Response) -> AppResult<()> {
let is_fragment = req.headers().get("X-Fragment-Header");
match is_fragment {
Expand Down
40 changes: 11 additions & 29 deletions templates/classic/diesel/src/beams/user.rs.liquid
Original file line number Diff line number Diff line change
@@ -1,20 +1,10 @@
use diesel::prelude::*;

use diesel::{ExpressionMethods, QueryDsl, RunQueryDsl, SelectableHelper};
use diesel::{ExpressionMethods, OptionalExtension, QueryDsl, RunQueryDsl, SelectableHelper};
use uuid::Uuid;

use crate::schema::users::dsl::users as diesel_users;
use crate::{
app_writer::AppResult,
db::establish_connection,
dtos::user::{
UserAddRequest, UserLoginRequest, UserLoginResponse, UserResponse, UserUpdateRequest,
},
middleware::jwt::get_token,
models::user::UserModel,
utils::rand_utils,
};
use diesel::OptionalExtension;
use crate::{db, hoops::jwt::get_token, utils::rand_utils, AppResult};

#[derive(Queryable, Selectable, Insertable)]
#[diesel(table_name = crate::schema::users)]
Expand All @@ -24,29 +14,21 @@ pub struct User {
pub password: String,
}

pub async fn add_user(req: UserAddRequest) -> AppResult<UserResponse> {
pub async fn add_user(req: UserAddRequest) -> AppResult<User> {
use crate::schema::users;
let mut db = establish_connection();
let model = UserModel {
let mut conn = db::connect()?;
let user = User {
id: Uuid::new_v4().to_string(),
username: req.username.clone(),
password: rand_utils::hash_password(req.password).await?,
};

diesel::insert_into(users::table)
.values(&model)
.execute(&mut db)
let user = diesel::insert_into(users::table)
.values(&user)
.get_result::<User>(&mut db)
.expect("Error saving new user");

let user: UserModel = users::table
.filter(users::id.eq(&model.id))
.first(&mut db)
.expect("Error loading user");

Ok(UserResponse {
id: user.id,
username: user.username,
})
Ok(user)
}

pub async fn login(req: UserLoginRequest) -> AppResult<UserLoginResponse> {
Expand All @@ -60,13 +42,13 @@ pub async fn login(req: UserLoginRequest) -> AppResult<UserLoginResponse> {
.optional()?;

match result {
None => Err(anyhow::anyhow!("{{user_does_not_exist}}").into()),
None => Err(AppError::public("{{user_does_not_exist}}")),
Some((uid, uname, hashed_pwd)) => {
if rand_utils::verify_password(req.password, hashed_pwd)
.await
.is_err()
{
return Err(anyhow::anyhow!("{{incorrect_password}}").into());
return Err(AppError::public("{{incorrect_password}}"));
}

let (token, exp) = get_token(uname.clone(), uid.clone())?;
Expand Down
3 changes: 3 additions & 0 deletions templates/classic/diesel/src/db/mod.rs.liquid
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@


use diesel::prelude::*;

use crate::config;

{% if db_type == "sqlite" %}
pub fn establish_connection() -> SqliteConnection {
let conn = SqliteConnection::establish(&config().db.database_url)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ pub struct Migration;

#[async_trait::async_trait]
impl MigrationTrait for Migration {
async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
async fn up(&self, manager: &SchemaManager) -> Result<(), DbError> {
manager
.create_table(
Table::create()
Expand All @@ -29,7 +29,7 @@ impl MigrationTrait for Migration {
.await
}

async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {
async fn down(&self, manager: &SchemaManager) -> Result<(), DbError> {
manager
.drop_table(Table::drop().table(Users::Table).to_owned())
.await
Expand Down

0 comments on commit 2f65bbb

Please sign in to comment.