Added shared state and changed to diesel orm
This commit is contained in:
parent
921e0a03d1
commit
38e4bbf3c2
|
@ -9,6 +9,7 @@ edition = "2021"
|
|||
dotenv = "0.15.0"
|
||||
serde = { version = "1.0", features = ["derive"] }
|
||||
tokio = { version = "1", features = ["full"] }
|
||||
sqlx = { version = "0.5", features = [ "runtime-tokio-rustls", "mysql" ] }
|
||||
#sqlx = { version = "0.5", features = [ "runtime-tokio-rustls", "mysql" ] }
|
||||
diesel = { version = "1.4.4", features = ["mysql"] }
|
||||
actix-web = "4"
|
||||
chrono = "0.4"
|
|
@ -1,7 +1,8 @@
|
|||
use std::collections::HashMap;
|
||||
use sqlx::{MySqlConnection, Connection};
|
||||
|
||||
pub async fn start_database_connection(env_vars: &HashMap<String, String>) -> Result<MySqlConnection, sqlx::Error>{
|
||||
use diesel::{MysqlConnection, Connection, ConnectionError};
|
||||
|
||||
pub async fn start_database_connection(env_vars: &HashMap<String, String>) -> Result<MysqlConnection, ConnectionError>{
|
||||
let db_user = match env_vars.get("DB_USER") {
|
||||
Some(str) => str,
|
||||
None => panic!("DB_USER env var not found")
|
||||
|
@ -18,5 +19,6 @@ pub async fn start_database_connection(env_vars: &HashMap<String, String>) -> Re
|
|||
Some(str) => str,
|
||||
None => panic!("DB_DATABASE_NAME env var not found")
|
||||
};
|
||||
MySqlConnection::connect(&format!("mysql://{db_user}:{db_pass}@{db_host}/{db_database_name}")).await
|
||||
let formatted_db_url = &format!("mysql://{db_user}:{db_pass}@{db_host}/{db_database_name}");
|
||||
MysqlConnection::establish(formatted_db_url)
|
||||
}
|
|
@ -1,8 +1,9 @@
|
|||
use sqlx::{ MySqlConnection};
|
||||
|
||||
use crate::r#do::user::User;
|
||||
|
||||
pub async fn _create_user_table_if_not_exists() -> Result<(), ()>{
|
||||
|
||||
pub async fn _insert_user(_conn: &mut MySqlConnection, _user: User) -> Result<(), sqlx::Error>{
|
||||
Ok(())
|
||||
}
|
||||
pub async fn _insert_user( _user: User) -> Result<(), ()>{
|
||||
Ok(())
|
||||
}
|
|
@ -1 +1,2 @@
|
|||
pub mod shared_state;
|
||||
pub mod user;
|
|
@ -0,0 +1,10 @@
|
|||
use std::collections::HashMap;
|
||||
|
||||
use diesel::MysqlConnection;
|
||||
|
||||
|
||||
|
||||
pub struct SharedStateObj{
|
||||
pub db_conn: MysqlConnection,
|
||||
pub env_vars: HashMap<String, String>,
|
||||
}
|
|
@ -1,6 +1,7 @@
|
|||
use diesel::Queryable;
|
||||
use serde::Serialize;
|
||||
|
||||
#[derive(Serialize)]
|
||||
#[derive(Serialize, Queryable)]
|
||||
pub struct User{
|
||||
pub id: u16,
|
||||
pub name: String
|
||||
|
|
12
src/main.rs
12
src/main.rs
|
@ -2,6 +2,7 @@ mod r#do; mod dao;
|
|||
mod routes; mod service;
|
||||
mod util;
|
||||
|
||||
use r#do::shared_state::SharedStateObj;
|
||||
use util::env_util;
|
||||
use routes::main_router::{start_all_routes, after_startup_fn};
|
||||
use dao::main_dao;
|
||||
|
@ -13,11 +14,14 @@ async fn main() -> Result<(), std::io::Error> {
|
|||
let env_vars = env_util::get_dot_env_map();
|
||||
|
||||
// Start database
|
||||
let _db_conn = match main_dao::start_database_connection(&env_vars).await {
|
||||
let db_conn = match main_dao::start_database_connection(&env_vars).await {
|
||||
Ok(conn) => conn,
|
||||
Err(e) => panic!("{}", e)
|
||||
Err(e) => panic!("Failure starting the database. Reason: {}", e)
|
||||
};
|
||||
|
||||
// Start server
|
||||
start_all_routes(&after_startup_fn, &env_vars).await
|
||||
// Put db connection and env variables in shared state
|
||||
let shared_state_obj = SharedStateObj {db_conn, env_vars };
|
||||
|
||||
// Pass shared state to server and start it
|
||||
start_all_routes(&after_startup_fn, shared_state_obj).await
|
||||
}
|
||||
|
|
|
@ -1,5 +1,7 @@
|
|||
use std::collections::HashMap;
|
||||
use actix_web::{HttpServer, App};
|
||||
use std::{sync::Mutex};
|
||||
use actix_web::{HttpServer, App, web};
|
||||
use crate::r#do::shared_state::SharedStateObj;
|
||||
|
||||
use super::user_routes;
|
||||
|
||||
// This function is to be used in case code is meant to be run after server startup
|
||||
|
@ -7,15 +9,16 @@ pub fn after_startup_fn(){
|
|||
println!("{}", "Started server.");
|
||||
}
|
||||
|
||||
pub async fn start_all_routes(after_startup_fn_call: &dyn Fn(), env_vars: &HashMap<String, String>)
|
||||
pub async fn start_all_routes(after_startup_fn_call: &dyn Fn(), state: SharedStateObj)
|
||||
-> Result<(), std::io::Error>
|
||||
{
|
||||
|
||||
// Get env variables to build server address
|
||||
let host_addr: &str = match env_vars.get("HOST_ADDRESS") {
|
||||
let host_addr: &str = match state.env_vars.get("HOST_ADDRESS") {
|
||||
Some(str) => {str},
|
||||
None => {panic!("HOST_ADDRESS env variable not found.");},
|
||||
};
|
||||
let host_port: u16 = match env_vars.get("HOST_PORT") {
|
||||
let host_port: u16 = match state.env_vars.get("HOST_PORT") {
|
||||
Some(str) => {
|
||||
match str.parse::<u16>() {
|
||||
Ok(resolved_port) => {resolved_port},
|
||||
|
@ -25,10 +28,17 @@ pub async fn start_all_routes(after_startup_fn_call: &dyn Fn(), env_vars: &HashM
|
|||
None => {panic!("HOST_PORT env variable not found.");},
|
||||
};
|
||||
|
||||
|
||||
// Extract variables to be put into shared app state & clone them
|
||||
let db_conn_state = web::Data::new(Mutex::new(state.db_conn));
|
||||
let env_vars_state = web::Data::new(Mutex::new(state.env_vars.clone()));
|
||||
|
||||
// Start server
|
||||
let server_future = HttpServer::new( || {
|
||||
let server_future = HttpServer::new( move || {
|
||||
App::new()
|
||||
// Define routes
|
||||
// Define routes & pass in shared state
|
||||
.app_data(db_conn_state.clone())
|
||||
.app_data(env_vars_state.clone())
|
||||
.service(user_routes::get_user_from_db)
|
||||
})
|
||||
.bind((host_addr, host_port))?
|
||||
|
@ -36,6 +46,5 @@ pub async fn start_all_routes(after_startup_fn_call: &dyn Fn(), env_vars: &HashM
|
|||
|
||||
let (server_start_result, _after_startup_value) =
|
||||
tokio::join!(server_future, async {after_startup_fn_call();});
|
||||
|
||||
return server_start_result; // Return server
|
||||
}
|
|
@ -1,8 +1,16 @@
|
|||
use actix_web::{get, web::{self, Path}, HttpResponse};
|
||||
use std::sync::Mutex;
|
||||
|
||||
use actix_web::{get, web::{self, Path, Data}, HttpResponse, post};
|
||||
use diesel::MysqlConnection;
|
||||
|
||||
use crate::r#do::user::User;
|
||||
|
||||
#[get("/user/{id}")]
|
||||
pub async fn get_user_from_db(id: Path<u16>) -> HttpResponse {
|
||||
pub async fn get_user_from_db(id: Path<u16>, _data: Data<Mutex<MysqlConnection>>) -> HttpResponse {
|
||||
HttpResponse::Ok().json(web::Json(User {id: *id, name: "nigga".to_string()}))
|
||||
}
|
||||
|
||||
#[post("/user")]
|
||||
pub async fn create_user() -> HttpResponse {
|
||||
HttpResponse::Ok().json(web::Json(""))
|
||||
}
|
Loading…
Reference in New Issue