feat: fixup "setup seaorm and a first "debug" entity as example"
This commit is contained in:
11
crates/backend/src/db.rs
Normal file
11
crates/backend/src/db.rs
Normal file
@ -0,0 +1,11 @@
|
||||
use migration::{Migrator, MigratorTrait};
|
||||
use sea_orm::{Database, DatabaseConnection, DbErr};
|
||||
use std::env;
|
||||
|
||||
pub async fn get_connection() -> Result<DatabaseConnection, DbErr> {
|
||||
let database_url = env::var("DATABASE_URL").expect("DATABASE_URL must be set");
|
||||
|
||||
let db_connection = Database::connect(database_url).await?;
|
||||
Migrator::up(&db_connection, None).await?;
|
||||
Ok(db_connection)
|
||||
}
|
@ -2,10 +2,13 @@ use anyhow::Error as AnyError;
|
||||
use axum::http::{StatusCode, Uri};
|
||||
use axum::response::{IntoResponse, Response};
|
||||
use axum::{routing::get, Router};
|
||||
use sea_orm::{DatabaseConnection, DbErr};
|
||||
use thiserror::Error;
|
||||
|
||||
use ::utils::config::{load_config, ConfigError};
|
||||
|
||||
mod db;
|
||||
|
||||
#[derive(Error, Debug)]
|
||||
pub enum InitError {
|
||||
#[error(transparent)]
|
||||
@ -17,10 +20,17 @@ pub fn init() -> Result<(), InitError> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn get_router() -> Router {
|
||||
Router::new()
|
||||
#[derive(Clone)]
|
||||
pub struct AppState {
|
||||
db_connection: DatabaseConnection,
|
||||
}
|
||||
|
||||
pub async fn get_router() -> Result<Router, DbErr> {
|
||||
let db_connection = db::get_connection().await?;
|
||||
|
||||
Ok(Router::new()
|
||||
.route("/", get(|| async { "Hello, world!" }))
|
||||
.fallback(fallback)
|
||||
.fallback(fallback))
|
||||
}
|
||||
|
||||
async fn fallback(uri: Uri) -> (StatusCode, String) {
|
||||
|
@ -10,16 +10,17 @@ pub enum BackendError {
|
||||
ServeTCPListener(#[from] std::io::Error),
|
||||
#[error("Error while initialising the backend")]
|
||||
InitError(#[from] InitError),
|
||||
#[error("Error with the database connection")]
|
||||
DatabaseConnection(#[from] sea_orm::DbErr),
|
||||
}
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<(), BackendError> {
|
||||
init()?;
|
||||
|
||||
let app = get_router();
|
||||
let app = get_router().await?;
|
||||
|
||||
let mut listenfd = ListenFd::from_env();
|
||||
|
||||
let listener = match listenfd.take_tcp_listener(0)? {
|
||||
// if we are given a tcp listener on listen fd 0, we use that one
|
||||
Some(listener) => {
|
||||
|
Reference in New Issue
Block a user