Skip to content

Commit

Permalink
Merge pull request #13 from salvo-rs/db
Browse files Browse the repository at this point in the history
fix js link
  • Loading branch information
fankaiLiu authored Nov 18, 2023
2 parents 14ee0a6 + df8ec78 commit 0b72c1e
Show file tree
Hide file tree
Showing 9 changed files with 68 additions and 21 deletions.
1 change: 1 addition & 0 deletions src/template/config/config.hbs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
name = "{{project_name}}"
address = "0.0.0.0:5800"
ssl = false
cors_allow_origin=["https://salvo.rs"]
{{#if need_db_conn}}
[database]
{{#if is_sea_orm_or_sqlx}}
Expand Down
1 change: 1 addition & 0 deletions src/template/src/config_template.hbs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ pub struct Configs {
pub struct Server {
pub name: String,
pub address: String,
pub cors_allow_origin: Vec<String>,
pub ssl: bool,
}
{{#if need_db_conn}}
Expand Down
11 changes: 11 additions & 0 deletions src/template/src/middleware/cors.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
use salvo::cors::{AllowHeaders, AllowMethods, Cors, CorsHandler};
use crate::config::CFG;

pub fn cors_middleware() -> CorsHandler {
let cors_handler = Cors::new()
.allow_origin(&CFG.server.cors_allow_origin)
.allow_methods(AllowMethods::any())
.allow_headers(AllowHeaders::any())
.into_handler();
cors_handler
}
2 changes: 1 addition & 1 deletion src/template/src/middleware/jwt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ pub struct JwtClaims {
}

#[allow(dead_code)]
pub fn jwt_hoop() -> JwtAuth<JwtClaims, ConstDecoder> {
pub fn jwt_middleware() -> JwtAuth<JwtClaims, ConstDecoder> {
let auth_handler: JwtAuth<JwtClaims, _> = JwtAuth::new(ConstDecoder::from_secret(
CFG.jwt.jwt_secret.to_owned().as_bytes(),
))
Expand Down
1 change: 1 addition & 0 deletions src/template/src/middleware/mod.rs
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
pub mod handle_404;
pub mod jwt;
pub mod cors;
33 changes: 27 additions & 6 deletions src/template/src/routers/mod.hbs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{{#if need_db_conn}}
{{#if is_web_site}}
use crate::middleware::jwt::jwt_hoop;
use crate::middleware::{cors::cors_middleware, jwt::jwt_middleware};
use salvo::{
prelude::{CatchPanic, Logger, OpenApi, SwaggerUi},
Router,
Expand All @@ -23,6 +23,8 @@ pub fn router() -> Router {
Router::with_path("/api/login").post(post_login),
];

let _cors_handler = cors_middleware();

let mut need_auth_routers = vec![
Router::with_path("users")
.get(user_list_page),
Expand All @@ -37,22 +39,23 @@ pub fn router() -> Router {
let static_routers = static_routers::create_static_routers();
no_auth_routers.extend(static_routers);
let router = Router::new()
//.hoop(_cors_handler)
.hoop(Logger::new())
.hoop(CatchPanic::new())
.get(hello)
.append(&mut no_auth_routers)
.push(
Router::new()
.append(&mut need_auth_routers)
.hoop(jwt_hoop()),
.hoop(jwt_middleware()),
);
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"))
}
{{else}}
use crate::middleware::jwt::jwt_hoop;
use crate::middleware::{cors::cors_middleware, jwt::jwt_middleware};
use salvo::{
prelude::{CatchPanic, Logger, OpenApi, SwaggerUi},
Router,
Expand All @@ -66,12 +69,15 @@ use self::{
};
pub mod demo;
pub mod user;
mod static_routers;

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

let _cors_handler = cors_middleware();

let mut need_auth_routers = vec![
Router::with_path("/api/users").get(get_users)
.post(post_add_user)
Expand All @@ -83,14 +89,15 @@ pub fn router() -> Router {
];

let router = Router::new()
//.hoop(_cors_handler)
.hoop(Logger::new())
.hoop(CatchPanic::new())
.get(hello)
.append(&mut no_auth_routers)
.push(
Router::new()
.append(&mut need_auth_routers)
.hoop(jwt_hoop()),
.hoop(jwt_middleware()),
);
let doc = OpenApi::new("salvo web api", "0.0.1").merge_router(&router);
router
Expand All @@ -104,13 +111,20 @@ use salvo::{
prelude::{CatchPanic, Logger, OpenApi, SwaggerUi},
Router,
};
use crate::middleware::cors::cors_middleware;
use self::demo::hello;
pub mod demo;
mod static_routers;

pub fn router() -> Router {
let _cors_handler = cors_middleware();
let mut static_routers = static_routers::create_static_routers();
let router = Router::new()
//.hoop(_cors_handler)
.hoop(Logger::new())
.hoop(CatchPanic::new())
.get(hello);
.get(hello)
.append(&mut static_routers);
let doc = OpenApi::new("salvo web api", "0.0.1").merge_router(&router);
router
.push(doc.into_router("/api-doc/openapi.json"))
Expand All @@ -121,13 +135,20 @@ use salvo::{
prelude::{CatchPanic, Logger, OpenApi, SwaggerUi},
Router,
};
use crate::middleware::cors::cors_middleware;
use self::demo::hello;
pub mod demo;
mod static_routers;

pub fn router() -> Router {
let _cors_handler = cors_middleware();
let mut static_routers = static_routers::create_static_routers();
let router = Router::new()
//.hoop(_cors_handler)
.hoop(Logger::new())
.hoop(CatchPanic::new())
.get(hello);
.get(hello)
.append(&mut static_routers);
let doc = OpenApi::new("salvo web api", "0.0.1").merge_router(&router);
router
.push(doc.into_router("/api-doc/openapi.json"))
Expand Down
5 changes: 4 additions & 1 deletion src/template/src/routers/static_routers.hbs
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
use rust_embed::RustEmbed;
{{#if need_db_conn}}
use salvo::{Router, serve_static::static_embed, endpoint, Response, http::ResBody, hyper::body::Bytes};

{{else}}
use salvo::{Router, endpoint, Response, http::ResBody, hyper::body::Bytes};
{{/if}}
#[derive(RustEmbed)]
#[folder = "assets"]
struct Assets;
Expand Down
4 changes: 4 additions & 0 deletions src/template/templates/404.hbs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,11 @@
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>404 {{page_not_found}}</title>
{{#if need_db_conn}}
<script src="assets/js/tailwindcss.js"></script>
{{else}}
<script src="https://cdn.tailwindcss.com"></script>
{{/if}}
</head>
<body
class="grid min-h-full place-items-center bg-white px-6 py-24 sm:py-32 lg:px-8"
Expand Down
31 changes: 18 additions & 13 deletions src/utils/create_project.rs
Original file line number Diff line number Diff line change
Expand Up @@ -124,11 +124,12 @@ pub fn write_project_file(
"once_cell": "1.18.0",
"salvo": {
"version": "0.58",
"features": ["anyhow", "logging", "cors", "oapi", "jwt-auth", "rustls", "catch-panic","cookie"]
"features": ["anyhow", "logging", "cors", "oapi", "jwt-auth", "rustls", "catch-panic","cookie","serve-static"]
},
"serde": "1.0.188",
"thiserror": "1.0.48",
"time": "0.3.28",
"rust-embed":"8.0.0",
"tokio": {
"version": "1",
"features": ["full"]
Expand Down Expand Up @@ -175,14 +176,20 @@ pub fn write_project_file(
let mut dependencies = data["dependencies"].clone();
handle_dependencies(
&mut dependencies,
is_web_site,
need_db_conn,
user_selected.db_type,
user_selected.db_conn_type,
);
data["dependencies"] = dependencies;

let (src_path, router_path) = create_basic_file(project_path, &handlebars, &data)?;
//assets
let assets_path = project_path.join("assets");
std::fs::create_dir_all(&assets_path)?;
//assets/favicon.ico
let favicon_bytes = include_bytes!("../template/assets/favicon.ico");
let mut favicon_file = File::create(assets_path.join("favicon.ico"))?;
favicon_file.write_all(favicon_bytes)?;

if is_web_site {
//templates
Expand Down Expand Up @@ -627,6 +634,10 @@ fn create_basic_file(
let handle404_rendered = handlebars.render_template(handle404_template, &data)?;
let mut handle404_file = File::create(middleware_path.join("handle_404.rs"))?;
handle404_file.write_all(handle404_rendered.as_bytes())?;
//src/middleware/cors.rs
let cors_bytes = include_bytes!("../template/src/middleware/cors.rs");
let mut cors_file = File::create(middleware_path.join("cors.rs"))?;
cors_file.write_all(cors_bytes)?;

//config
let config_path = project_path.join("config");
Expand Down Expand Up @@ -661,6 +672,11 @@ fn create_basic_file(
let router_demo_rendered = handlebars.render_template(router_demo_template, &data)?;
let mut router_demo_file = File::create(router_path.join("demo.rs"))?;
router_demo_file.write_all(router_demo_rendered.as_bytes())?;
//src/router/static_routers.rs
let router_static_template = include_str!("../template/src/routers/static_routers.hbs");
let router_static_rendered = handlebars.render_template(router_static_template, &data)?;
let mut router_static_file = File::create(router_path.join("static_routers.rs"))?;
router_static_file.write_all(router_static_rendered.as_bytes())?;

//src/router/static_routers.rs
// let router_static_routers_template = include_str!("../template/src/routers/static_routers.hbs");
Expand All @@ -673,21 +689,10 @@ fn create_basic_file(

fn handle_dependencies(
dependencies: &mut serde_json::Value,
is_website: bool,
need_db_conn: bool,
db_type: DbType,
conn_type: DbConnectionType,
) {
if is_website {
dependencies["rust-embed"] = json!({
"version": "8.0.0",
});
if let Some(salvo) = dependencies["salvo"].as_object_mut() {
if let Some(features) = salvo["features"].as_array_mut() {
features.push(serde_json::json!("serve-static"));
}
}
}
if need_db_conn {
match (conn_type, db_type) {
(DbConnectionType::Sqlx, DbType::Mysql) => {
Expand Down

0 comments on commit 0b72c1e

Please sign in to comment.