Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

mongodb #8

Merged
merged 7 commits into from
Nov 13, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "salvo-cli"
version = "0.1.19"
version = "0.1.20"
edition = "2021"
authors = ["Fankai Liu [email protected]"]
keywords = ["salvo", "cli","template"]
Expand Down
5 changes: 4 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -98,8 +98,11 @@ cargo install --force salvo-cli
| ✅ | web site template |
| ✅ | Template with SQLx, SeaORM, Diesel, Rbatis (support for SQLite, PostgreSQL, MySQL) |
| ✅ | Basic middleware |
| ✅ | Support for MongoDB |
| ⏳ | More middleware |
| ⏳ | Support for MongoDB |
| ⏳ | Support for docker |
| ⏳ | More integrations with good crates (validation, embedding, permissions or others?) |
| ⏳ | Split into multiple crates for clearer code organization |

## License

Expand Down
18 changes: 18 additions & 0 deletions locales/app.yml
Original file line number Diff line number Diff line change
Expand Up @@ -347,6 +347,24 @@ db_conn_types_rbatis:
th: rbatis:เฟรมเวิร์ก ORM แบบ async ที่คล้ายกับ Mybatis (java)
el: rbatis:ένα παρόμοιο Mybatis (java) ασύγχρονο πλαίσιο ORM
da: rbatis:Et lignende Mybatis (java) asynkront ORM-rammeverk
db_conn_types_mongodb:
en: The official MongoDB driver for Rust
zh_CN: Rust 的官方 MongoDB 驱动程序
zh_TW: Rust 的官方 MongoDB 驱動程式
fr: Le pilote MongoDB officiel pour Rust
ja: Rust の公式 MongoDB ドライバー
es: El controlador MongoDB oficial para Rust
de: Der offizielle MongoDB-Treiber für Rust
ru: Официальный драйвер MongoDB для Rust
it: Il driver MongoDB ufficiale per Rust
pt: O driver oficial do MongoDB para Rust
ko: Rust의 공식 MongoDB 드라이버
no: Den offisielle MongoDB-driveren for Rust
is: Opinber MongoDB keyrir fyrir Rust
uk: Офіційний драйвер MongoDB для Rust
th: ไดร์เวอร์ MongoDB อย่างเป็นทางการสำหรับ Rust
el: Ο επίσημος οδηγός MongoDB για Rust
da: Den officielle MongoDB-driver for Rust
db_conn_types_nothing:
en: unnecessary
zh_CN: 不需要
Expand Down
18 changes: 18 additions & 0 deletions locales/code_comment.yml
Original file line number Diff line number Diff line change
Expand Up @@ -580,3 +580,21 @@ create_success_sqlx_diesel:
th: 🎯 สร้างฐานข้อมูลเริ่มต้นใน `/data/test.db`. \n หลังจากเรียกใช้งาน คุณสามารถเข้าถึง /login ด้วยชื่อผู้ใช้เริ่มต้น:zhangsan และรหัสผ่าน:123
el: 🎯 Δημιουργήθηκε η προεπιλεγμένη βάση δεδομένων στο `/data/test.db`. \n Μετά την εκτέλεσή του, μπορείτε να αποκτήσετε πρόσβαση στο /login με το όνομα χρήστη:zhangsan και τον κωδικό πρόσβασης:123
da: 🎯 Standarddatabasen er oprettet i `/data/test.db`. \n Efter at have kørt det, kan du få adgang til /login med standardbrugernavnet:zhangsan og adgangskoden:123
mongodb_usage_import_user_data:
en: 🎯 Please first run the program, then import data from data/user.json into the user table
zh_CN: 🎯 请首先运行程序,然后将 data/user.json 中的数据导入到 user 表中
zh_TW: 🎯 請先運行程序,然後將 data/user.json 中的數據導入到 user 表中
fr: 🎯 Veuillez d'abord exécuter le programme, puis importer les données de data/user.json dans la table utilisateur
ja: 🎯 プログラムを最初に実行し、その後、data/user.json からデータを user テーブルにインポートしてください
es: 🎯 Por favor, primero ejecute el programa, luego importe los datos de data/user.json a la tabla de usuarios
de: 🎯 Bitte führen Sie zuerst das Programm aus und importieren Sie dann die Daten aus data/user.json in die Benutzertabelle
ru: 🎯 Пожалуйста, сначала запустите программу, затем импортируйте данные из data/user.json в таблицу пользователей
it: 🎯 Si prega di eseguire prima il programma, poi importare i dati da data/user.json nella tabella degli utenti
pt: 🎯 Por favor, primeiro execute o programa, depois importe os dados de data/user.json para a tabela de usuários
ko: 🎯 먼저 프로그램을 실행한 다음, data/user.json의 데이터를 사용자 테이블에 가져와 주세요.
no: 🎯 Vennligst kjør først programmet, deretter importer data fra data/user.json inn i brukertabellen
is: 🎯 Vinsamlegast keyraðu fyrst forritið, síðan flytjaðu gögn úr data/user.json inn í notandatafluna
uk: 🎯 Будь ласка, спочатку запустіть програму, а потім імпортуйте дані з data/user.json до таблиці користувачів
th: 🎯 โปรดเรียกใช้โปรแกรมก่อน, จากนั้นนำเข้าข้อมูลจาก data/user.json ไปยังตารางผู้ใช้
el: 🎯 Παρακαλώ πρώτα τρέξτε το πρόγραμμα, στη συνέχεια εισάγετε τα δεδομένα από το data/user.json στον πίνακα χρήστη
da: 🎯 Kør venligst først programmet, importér derefter data fra data/user.json ind i brugertabellen
2 changes: 1 addition & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use i18n::set_locale;
mod i18n;
rust_i18n::i18n!("locales", fallback = "en");
#[derive(Parser, Debug)]
#[clap(version = "0.1.19", author = "Fankai liu <[email protected]>")]
#[clap(version = "0.1.20", author = "Fankai liu <[email protected]>")]
struct Opts {
#[clap(subcommand)]
subcmd: SubCommand,
Expand Down
3 changes: 3 additions & 0 deletions src/template/config/config.hbs
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,9 @@ database_url="mssql://SA:TestPass!123456@localhost:1433/rbatis_example"
{{/if}}
{{/if}}
{{/if}}
{{#if is_mongodb}}
database_url="mongodb://localhost:27017"
{{/if}}
[jwt]
jwt_secret = "secret"
jwt_exp = 6000
Expand Down
7 changes: 7 additions & 0 deletions src/template/data/users.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
[
{
"_id": "65507c75ae575ce9f420eb97",
"password": "$argon2id$v=19$m=19456,t=2,p=1$BL/Ly2chRn33DZJePPniYQ$kzJ24lG8j0GR+6Q7PmHUiE7JxlQfomB5svwDwnoL0Ng",
"username": "zhangsan"
}
]
13 changes: 13 additions & 0 deletions src/template/src/app_error.hbs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,11 @@ use salvo::{
Depot, Request, Response, Writer,
};
{{/if}}
{{#if is_mongodb}}
use mongodb::bson::document::ValueAccessError as MongoBsonAccessError;
use mongodb::bson::oid::Error as MongoBsonOidError;
use mongodb::error::Error as MongoDbError;
{{/if}}
use thiserror::Error;

#[derive(Error, Debug)]
Expand All @@ -39,6 +44,14 @@ pub enum AppError {
#[error("rbatis::Error:`{0}`")]
RbatisErr(#[from] rbatis::Error),
{{/if}}
{{#if is_mongodb}}
#[error("mongodb::error::Error:`{0}`")]
MongoDbErr(#[from] MongoDbError),
#[error("mongodb::bson::document::ValueAccessError:`{0}`")]
MongoBsonAccessError(#[from] MongoBsonAccessError),
#[error("mongodb::bson::oid::Error`{0}`")]
MongoBsonOidError(#[from] MongoBsonOidError),
{{/if}}
}

pub type AppResult<T> = Result<T, AppError>;
Expand Down
28 changes: 26 additions & 2 deletions src/template/src/db.hbs
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,6 @@ pub async fn init_db_conn() {
.await;
}
{{/if}}

{{#if is_sea_orm}}
pub static DB: OnceCell<DatabaseConnection> = OnceCell::const_new();

Expand All @@ -90,7 +89,6 @@ pub async fn init_db_conn() {
.await;
}
{{/if}}

{{#if is_rbatis}}
use tokio::sync::OnceCell;
use rbatis::rbatis::RBatis;
Expand Down Expand Up @@ -133,3 +131,29 @@ pub async fn init_db_conn() {
.await;
}
{{/if}}
{{#if is_mongodb}}
use crate::entities::user::User;
use mongodb::{bson::doc, options::IndexOptions, Client, IndexModel};
use once_cell::sync::OnceCell;
pub const DB_NAME: &str = "myApp";
pub const COLL_NAME: &str = "users";
pub static MONGODB_CLIENT: OnceCell<Client> = OnceCell::new();
pub async fn init_db_conn() {
let mongodb_uri = &CFG.database.database_url;
let client = Client::with_uri_str(mongodb_uri)
.await
.expect("failed to connect");
let options = IndexOptions::builder().unique(true).build();
let model = IndexModel::builder()
.keys(doc! { "username": 1 })
.options(options)
.build();
client
.database(DB_NAME)
.collection::<User>(COLL_NAME)
.create_index(model, None)
.await
.expect("creating an index should succeed");
MONGODB_CLIENT.get_or_init(|| client);
}
{{/if}}
3 changes: 3 additions & 0 deletions src/template/src/entities/mod.hbs
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,7 @@ pub mod user;
{{/if}}
{{#if is_rbatis}}
pub mod user;
{{/if}}
{{#if is_mongodb}}
pub mod user;
{{/if}}
11 changes: 11 additions & 0 deletions src/template/src/entities/user.hbs
Original file line number Diff line number Diff line change
Expand Up @@ -40,4 +40,15 @@ pub struct Users{
}

crud!(Users {});
{{/if}}
{{#if is_mongodb}}
use mongodb::bson::oid::ObjectId;
use serde::{Deserialize, Serialize};

#[derive(Debug, Deserialize, Serialize)]
pub struct User {
_id: Option<ObjectId>,
pub username: String,
pub password: String,
}
{{/if}}
9 changes: 9 additions & 0 deletions src/template/src/main_template.hbs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@ use crate::db::init_db_conn;
{{#if is_rbatis}}
use crate::db::init_db_conn;
{{/if}}
{{#if is_mongodb}}
use crate::db::init_db_conn;
{{/if}}
use crate::middleware::handle_404::handle_404;
use crate::routers::router;
use config::{CERT_KEY, CFG};
Expand All @@ -27,6 +30,9 @@ mod utils;
{{#if is_sea_orm_or_sqlx}}
mod entities;
{{/if}}
{{#if is_mongodb}}
mod entities;
{{/if}}
{{#if is_diesel}}
mod models;
mod schema;
Expand All @@ -47,6 +53,9 @@ async fn main() {
{{#if is_rbatis}}
init_db_conn().await;
{{/if}}
{{#if is_mongodb}}
init_db_conn().await;
{{/if}}
let (tx, rx) = oneshot::channel();
let router = router();
let service: Service = router.into();
Expand Down
Loading
Loading