Add migrations and user models crud
This commit is contained in:
parent
2141c992d7
commit
30be91390b
13 changed files with 473 additions and 47 deletions
10
src/lib.rs
10
src/lib.rs
|
|
@ -1,13 +1,17 @@
|
|||
use axum::{Router, routing::get};
|
||||
use axum::{
|
||||
Router,
|
||||
routing::{delete, get, post},
|
||||
};
|
||||
use static_serve::embed_assets;
|
||||
|
||||
use crate::state::AppState;
|
||||
|
||||
mod migrations;
|
||||
mod models;
|
||||
mod routes;
|
||||
pub mod state;
|
||||
|
||||
pub fn build_app(state: AppState) -> Router {
|
||||
println!("{:?}", state);
|
||||
embed_assets!("assets", compress = true);
|
||||
|
||||
Router::new()
|
||||
|
|
@ -16,6 +20,8 @@ pub fn build_app(state: AppState) -> Router {
|
|||
.route("/books/{id}/edit", get(routes::book::edit))
|
||||
.route("/books/new", get(routes::book::new))
|
||||
.route("/users", get(routes::user::index))
|
||||
.route("/users", post(routes::user::create))
|
||||
.route("/users/{id}", post(routes::user::delete))
|
||||
.nest("/assets", static_router())
|
||||
.with_state(state)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -6,7 +6,7 @@ use bookforge::build_app;
|
|||
use bookforge::state::AppState;
|
||||
|
||||
#[derive(Snafu, Debug)]
|
||||
enum AppError {
|
||||
pub enum AppError {
|
||||
#[snafu(display("Failed to initialize AppState"))]
|
||||
State {
|
||||
source: AppStateError,
|
||||
|
|
@ -16,8 +16,9 @@ enum AppError {
|
|||
|
||||
async fn main_inner() -> Result<(), AppError> {
|
||||
pretty_env_logger::init();
|
||||
let app_state = AppState::new().await.context(StateSnafu)?;
|
||||
|
||||
let app = build_app(AppState::new().await.context(StateSnafu)?);
|
||||
let app = build_app(app_state);
|
||||
|
||||
let listener = tokio::net::TcpListener::bind("0.0.0.0:8000").await.unwrap();
|
||||
|
||||
|
|
|
|||
33
src/migrations/m20260126_000001_create_user_table.rs
Normal file
33
src/migrations/m20260126_000001_create_user_table.rs
Normal file
|
|
@ -0,0 +1,33 @@
|
|||
use sea_orm_migration::{prelude::*, schema::*};
|
||||
|
||||
#[derive(DeriveMigrationName)]
|
||||
pub struct Migration;
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl MigrationTrait for Migration {
|
||||
async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
|
||||
manager
|
||||
.create_table(
|
||||
Table::create()
|
||||
.table(User::Table)
|
||||
.if_not_exists()
|
||||
.col(pk_auto(User::Id))
|
||||
.col(string(User::Name).unique_key())
|
||||
.to_owned(),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {
|
||||
manager
|
||||
.drop_table(Table::drop().table(User::Table).to_owned())
|
||||
.await
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(DeriveIden)]
|
||||
pub enum User {
|
||||
Table,
|
||||
Id,
|
||||
Name,
|
||||
}
|
||||
39
src/migrations/m20260126_000002_create_book_table.rs
Normal file
39
src/migrations/m20260126_000002_create_book_table.rs
Normal file
|
|
@ -0,0 +1,39 @@
|
|||
use sea_orm_migration::{prelude::*, schema::*};
|
||||
|
||||
#[derive(DeriveMigrationName)]
|
||||
pub struct Migration;
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl MigrationTrait for Migration {
|
||||
async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
|
||||
manager
|
||||
.create_table(
|
||||
Table::create()
|
||||
.table(Book::Table)
|
||||
.if_not_exists()
|
||||
.col(pk_auto(Book::Id))
|
||||
.col(string(Book::Title))
|
||||
.col(string(Book::Authors))
|
||||
.col(text(Book::Description))
|
||||
.col(text(Book::Comment))
|
||||
.to_owned(),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {
|
||||
manager
|
||||
.drop_table(Table::drop().table(Book::Table).to_owned())
|
||||
.await
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(DeriveIden)]
|
||||
pub enum Book {
|
||||
Table,
|
||||
Id,
|
||||
Title,
|
||||
Authors,
|
||||
Description,
|
||||
Comment,
|
||||
}
|
||||
16
src/migrations/mod.rs
Normal file
16
src/migrations/mod.rs
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
pub use sea_orm_migration::prelude::*;
|
||||
|
||||
mod m20260126_000001_create_user_table;
|
||||
mod m20260126_000002_create_book_table;
|
||||
|
||||
pub struct Migrator;
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl MigratorTrait for Migrator {
|
||||
fn migrations() -> Vec<Box<dyn MigrationTrait>> {
|
||||
vec![
|
||||
Box::new(m20260126_000001_create_user_table::Migration),
|
||||
Box::new(m20260126_000002_create_book_table::Migration),
|
||||
]
|
||||
}
|
||||
}
|
||||
1
src/models/mod.rs
Normal file
1
src/models/mod.rs
Normal file
|
|
@ -0,0 +1 @@
|
|||
pub mod user;
|
||||
64
src/models/user.rs
Normal file
64
src/models/user.rs
Normal file
|
|
@ -0,0 +1,64 @@
|
|||
use crate::routes::user::UserForm;
|
||||
use crate::state::AppState;
|
||||
use sea_orm::ActiveValue::Set;
|
||||
use sea_orm::DeleteResult;
|
||||
use sea_orm::entity::prelude::*;
|
||||
use snafu::ResultExt;
|
||||
use snafu::prelude::*;
|
||||
|
||||
#[sea_orm::model]
|
||||
#[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel)]
|
||||
#[sea_orm(table_name = "user")]
|
||||
pub struct Model {
|
||||
#[sea_orm(primary_key)]
|
||||
pub id: i32,
|
||||
pub name: String,
|
||||
// #[sea_orm(has_many)]
|
||||
// pub book: HasMany<super::profile::Entity>,
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl ActiveModelBehavior for ActiveModel {}
|
||||
|
||||
#[derive(Debug, Snafu)]
|
||||
#[snafu(visibility(pub))]
|
||||
pub enum UserError {
|
||||
// #[snafu(display("The Content Folder (Path: {path}) does not exist"))]
|
||||
// NotFound { path: String },
|
||||
#[snafu(display("Database error"))]
|
||||
DB { source: sea_orm::DbErr },
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct UserOperator {
|
||||
pub state: AppState,
|
||||
}
|
||||
|
||||
impl UserOperator {
|
||||
pub fn new(state: AppState) -> Self {
|
||||
Self { state }
|
||||
}
|
||||
|
||||
pub async fn list(&self) -> Result<Vec<Model>, UserError> {
|
||||
Entity::find().all(&self.state.db).await.context(DBSnafu)
|
||||
}
|
||||
|
||||
pub async fn create(&self, form: UserForm) -> Result<Model, UserError> {
|
||||
let user = ActiveModel {
|
||||
name: Set(form.name),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
user.insert(&self.state.db).await.context(DBSnafu)
|
||||
}
|
||||
|
||||
pub async fn delete(&self, user_id: i32) -> Result<DeleteResult, UserError> {
|
||||
let user: Option<Model> = Entity::find_by_id(user_id)
|
||||
.one(&self.state.db)
|
||||
.await
|
||||
.context(DBSnafu)?;
|
||||
let user: Model = user.unwrap();
|
||||
|
||||
user.delete(&self.state.db).await.context(DBSnafu)
|
||||
}
|
||||
}
|
||||
|
|
@ -1,16 +1,60 @@
|
|||
use askama::Template;
|
||||
use askama_web::WebTemplate;
|
||||
use axum::{
|
||||
Form,
|
||||
extract::{Path, State},
|
||||
response::Redirect,
|
||||
};
|
||||
use serde::Deserialize;
|
||||
use snafu::prelude::*;
|
||||
|
||||
use crate::state::error::AppStateError;
|
||||
use crate::{
|
||||
models::user::{self, UserOperator},
|
||||
state::{
|
||||
AppState,
|
||||
error::{AppStateError, UserSnafu},
|
||||
},
|
||||
};
|
||||
|
||||
#[derive(Template, WebTemplate)]
|
||||
#[template(path = "users/index.html")]
|
||||
struct UsersIndexTemplate {}
|
||||
|
||||
pub async fn index() -> Result<impl axum::response::IntoResponse, AppStateError> {
|
||||
if 0 > 1 {
|
||||
return Err(AppStateError::Error);
|
||||
}
|
||||
|
||||
Ok(UsersIndexTemplate {})
|
||||
struct UsersIndexTemplate {
|
||||
users: Vec<user::Model>,
|
||||
}
|
||||
|
||||
pub async fn index(
|
||||
State(state): State<AppState>,
|
||||
) -> Result<impl axum::response::IntoResponse, AppStateError> {
|
||||
let users = UserOperator::new(state).list().await.context(UserSnafu)?;
|
||||
|
||||
Ok(UsersIndexTemplate { users })
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct UserForm {
|
||||
pub name: String,
|
||||
}
|
||||
|
||||
pub async fn create(
|
||||
State(state): State<AppState>,
|
||||
Form(form): Form<UserForm>,
|
||||
) -> Result<impl axum::response::IntoResponse, AppStateError> {
|
||||
let _user = UserOperator::new(state)
|
||||
.create(form)
|
||||
.await
|
||||
.context(UserSnafu)?;
|
||||
|
||||
Ok(Redirect::to("/users"))
|
||||
}
|
||||
|
||||
pub async fn delete(
|
||||
State(state): State<AppState>,
|
||||
Path(id): Path<i32>,
|
||||
) -> Result<impl axum::response::IntoResponse, AppStateError> {
|
||||
let _user = UserOperator::new(state)
|
||||
.delete(id)
|
||||
.await
|
||||
.context(UserSnafu)?;
|
||||
|
||||
Ok(Redirect::to("/users"))
|
||||
}
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@ use askama_web::WebTemplate;
|
|||
use axum::response::{IntoResponse, Response};
|
||||
use snafu::prelude::*;
|
||||
|
||||
use crate::state::config::ConfigError;
|
||||
use crate::{models::user::UserError, state::config::ConfigError};
|
||||
|
||||
#[derive(Template, WebTemplate)]
|
||||
#[template(path = "error.html")]
|
||||
|
|
@ -21,6 +21,14 @@ pub enum AppStateError {
|
|||
ConfigError {
|
||||
source: ConfigError,
|
||||
},
|
||||
#[snafu(display("Migration Error"))]
|
||||
Migration {
|
||||
source: sea_orm::error::DbErr,
|
||||
},
|
||||
#[snafu(display("User Model Error"))]
|
||||
User {
|
||||
source: UserError,
|
||||
},
|
||||
}
|
||||
|
||||
impl IntoResponse for AppStateError {
|
||||
|
|
|
|||
|
|
@ -1,8 +1,9 @@
|
|||
use sea_orm::{Database, DatabaseConnection};
|
||||
use snafu::prelude::*;
|
||||
|
||||
use crate::state::config::AppConfig;
|
||||
use crate::{migrations::Migrator, state::config::AppConfig};
|
||||
use error::*;
|
||||
use sea_orm_migration::MigratorTrait;
|
||||
|
||||
pub mod config;
|
||||
pub mod error;
|
||||
|
|
@ -15,6 +16,7 @@ pub struct AppState {
|
|||
|
||||
impl AppState {
|
||||
pub async fn new() -> Result<Self, AppStateError> {
|
||||
log::info!("Load configurations...");
|
||||
let config: AppConfig = AppConfig::new().await.context(ConfigSnafu)?;
|
||||
|
||||
let db: DatabaseConnection =
|
||||
|
|
@ -22,6 +24,10 @@ impl AppState {
|
|||
.await
|
||||
.context(SqliteSnafu)?;
|
||||
|
||||
log::info!("Database Loaded at : {}", config.database_path.clone());
|
||||
|
||||
Migrator::up(&db, None).await.context(MigrationSnafu)?;
|
||||
|
||||
Ok(Self { config, db })
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in a new issue