first commit

This commit is contained in:
2022-08-31 11:40:50 +05:30
parent b337811f48
commit 1e499087b0
15 changed files with 365 additions and 0 deletions

31
backend/Cargo.toml Normal file
View File

@@ -0,0 +1,31 @@
[package]
name = "backend"
version = "0.1.0"
edition = "2021"
[workspace]
members = [".", "entity", "migration"]
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
axum = "^0.5"
axum-extra = { version = "^0.3", features = ["spa"] }
clap = { version = "^3", features = ["derive"] }
log = "^0.4"
serde = { version = "^1.0", features = ["derive"] }
serde_json = "^1.0"
tokio = { version = "^1", features = ["full"] }
tower = "^0.4"
tower-http = { version = "^0.3", features = ["full"] }
tracing = "^0.1"
tracing-subscriber = "^0.3"
[dependencies.sea-orm]
version = "^0.9.2" # sea-orm version
features = [
"debug-print",
"runtime-tokio-native-tls",
"sqlx-sqlite",
]

15
backend/entity/Cargo.toml Normal file
View File

@@ -0,0 +1,15 @@
[package]
name = "entity"
version = "0.1.0"
edition = "2021"
publish = false
[lib]
name = "entity"
path = "src/lib.rs"
[dependencies]
serde = { version = "1", features = ["derive"] }
[dependencies.sea-orm]
version = "^0.9.2" # sea-orm version

View File

@@ -0,0 +1 @@
pub mod post;

View File

@@ -0,0 +1,26 @@
//! SeaORM Entity. Generated by sea-orm-codegen 0.3.2
use sea_orm::entity::prelude::*;
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel, Serialize, Deserialize)]
#[sea_orm(table_name = "posts")]
pub struct Model {
#[sea_orm(primary_key)]
#[serde(skip_deserializing)]
pub id: i32,
pub title: String,
#[sea_orm(column_type = "Text")]
pub text: String,
}
#[derive(Copy, Clone, Debug, EnumIter)]
pub enum Relation {}
impl RelationTrait for Relation {
fn def(&self) -> RelationDef {
panic!("No RelationDef")
}
}
impl ActiveModelBehavior for ActiveModel {}

View File

@@ -0,0 +1,20 @@
[package]
name = "migration"
version = "0.1.0"
edition = "2021"
publish = false
[lib]
name = "migration"
path = "src/lib.rs"
[dependencies]
async-std = { version = "^1", features = ["attributes", "tokio1"] }
[dependencies.sea-orm-migration]
version = "^0.9.2" # sea-orm-migration version
features = [
# Enable following runtime and db backend features if you want to run migration via CLI
# "runtime-tokio-native-tls",
# "sqlx-postgres",
]

View File

@@ -0,0 +1,37 @@
# Running Migrator CLI
- Apply all pending migrations
```sh
cargo run
```
```sh
cargo run -- up
```
- Apply first 10 pending migrations
```sh
cargo run -- up -n 10
```
- Rollback last applied migrations
```sh
cargo run -- down
```
- Rollback last 10 applied migrations
```sh
cargo run -- down -n 10
```
- Drop all tables from the database, then reapply all migrations
```sh
cargo run -- fresh
```
- Rollback all applied migrations, then reapply all migrations
```sh
cargo run -- refresh
```
- Rollback all applied migrations
```sh
cargo run -- reset
```
- Check the status of all migrations
```sh
cargo run -- status
```

View File

@@ -0,0 +1,12 @@
pub use sea_orm_migration::prelude::*;
mod m20220120_000001_create_post_table;
pub struct Migrator;
#[async_trait::async_trait]
impl MigratorTrait for Migrator {
fn migrations() -> Vec<Box<dyn MigrationTrait>> {
vec![Box::new(m20220120_000001_create_post_table::Migration)]
}
}

View File

@@ -0,0 +1,42 @@
use sea_orm_migration::prelude::*;
#[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(Posts::Table)
.if_not_exists()
.col(
ColumnDef::new(Posts::Id)
.integer()
.not_null()
.auto_increment()
.primary_key(),
)
.col(ColumnDef::new(Posts::Title).string().not_null())
.col(ColumnDef::new(Posts::Text).string().not_null())
.to_owned(),
)
.await
}
async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {
manager
.drop_table(Table::drop().table(Posts::Table).to_owned())
.await
}
}
/// Learn more at https://docs.rs/sea-query#iden
#[derive(Iden)]
enum Posts {
Table,
Id,
Title,
Text,
}

View File

@@ -0,0 +1,6 @@
use sea_orm_migration::prelude::*;
#[async_std::main]
async fn main() {
cli::run_cli(migration::Migrator).await;
}

61
backend/src/main.rs Normal file
View File

@@ -0,0 +1,61 @@
use axum::{response::IntoResponse, routing::get, Router};
use axum_extra::routing::SpaRouter;
use clap::Parser;
use std::net::{IpAddr, Ipv6Addr, SocketAddr};
use std::str::FromStr;
use tower::ServiceBuilder;
use tower_http::trace::TraceLayer;
// Setup the command line interface with clap.
#[derive(Parser, Debug)]
#[clap(name = "server", about = "A server for our wasm project!")]
struct Opt {
/// set the log level
#[clap(short = 'l', long = "log", default_value = "debug")]
log_level: String,
/// set the listen addr
#[clap(short = 'a', long = "addr", default_value = "::1")]
addr: String,
/// set the listen port
#[clap(short = 'p', long = "port", default_value = "8080")]
port: u16,
/// set the directory where static files are to be found
#[clap(long = "static-dir", default_value = "../dist")]
static_dir: String,
}
#[tokio::main]
async fn main() {
let opt = Opt::parse();
// Setup logging & RUST_LOG from args
if std::env::var("RUST_LOG").is_err() {
std::env::set_var("RUST_LOG", format!("{},hyper=info,mio=info", opt.log_level))
}
// enable console logging
tracing_subscriber::fmt::init();
let app = Router::new()
.route("/api/hello", get(hello))
.merge(SpaRouter::new("/assets", opt.static_dir))
.layer(ServiceBuilder::new().layer(TraceLayer::new_for_http()));
let sock_addr = SocketAddr::from((
IpAddr::from_str(opt.addr.as_str()).unwrap_or(IpAddr::V6(Ipv6Addr::LOCALHOST)),
opt.port,
));
log::info!("listening on http://{}", sock_addr);
axum::Server::bind(&sock_addr)
.serve(app.into_make_service())
.await
.expect("Unable to start server");
}
async fn hello() -> impl IntoResponse {
"hello from server!"
}