rebuild file structur + simple sqlite db endpoint
This commit is contained in:
13
src/dto/rooms.rs
Normal file
13
src/dto/rooms.rs
Normal file
@@ -0,0 +1,13 @@
|
||||
use serde::Deserialize;
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct UpdateRoomStatusDto{
|
||||
pub room_number: i32,
|
||||
pub status: string,
|
||||
}
|
||||
|
||||
#[derive(Debug, Seserialize)]
|
||||
pub struct RoomStatusIdDto{
|
||||
pub room_number: i32,
|
||||
pub status: string,
|
||||
}
|
||||
6
src/lib.rs
Normal file
6
src/lib.rs
Normal file
@@ -0,0 +1,6 @@
|
||||
#[allow(unused_imports)]
|
||||
#[allow(dead_code)]
|
||||
|
||||
pub mod utils;
|
||||
pub mod routes;
|
||||
pub mod rooms;
|
||||
33
src/main.rs
33
src/main.rs
@@ -1,24 +1,23 @@
|
||||
use axum::{
|
||||
//response::Html,
|
||||
routing::get, //post,
|
||||
Router
|
||||
};
|
||||
use axum::serve;
|
||||
use tokio::net::TcpListener;
|
||||
|
||||
mod utils;
|
||||
mod routes;
|
||||
mod rooms;
|
||||
|
||||
use crate::utils::db_pool::HotelPools;
|
||||
use routes::create_router;
|
||||
|
||||
|
||||
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() {
|
||||
|
||||
let app : Router = routes::create_routes();
|
||||
|
||||
|
||||
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
|
||||
.await
|
||||
.unwrap();
|
||||
println!("listining on {}", listener.local_addr().unwrap() );
|
||||
|
||||
axum::serve(listener, app).await.unwrap();
|
||||
async fn main() -> std::io::Result<()> {
|
||||
let hotel_pools = HotelPools::new();
|
||||
let app = create_router(hotel_pools);
|
||||
let listener = TcpListener::bind("0.0.0.0:3000").await?;
|
||||
serve(listener, app).into_future().await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn handler() -> &'static str {
|
||||
|
||||
39
src/rooms/extractor.rs
Normal file
39
src/rooms/extractor.rs
Normal file
@@ -0,0 +1,39 @@
|
||||
use axum::{
|
||||
extract::{Request, FromRequest, Path},
|
||||
body::{Body},
|
||||
|
||||
http::StatusCode,
|
||||
Json, Router,
|
||||
};
|
||||
use serde::Deserialize;
|
||||
|
||||
#[derive(Deserialize, Debug)]
|
||||
pub struct UpdateRoomValues {
|
||||
pub status: String,
|
||||
pub token: String,
|
||||
pub hotel_id: i32,
|
||||
}
|
||||
|
||||
pub struct UpdateRoomPayload(pub UpdateRoomValues);
|
||||
|
||||
//#[async_trait]
|
||||
impl<S> FromRequest<S> for UpdateRoomPayload
|
||||
where S: Send + Sync,
|
||||
{
|
||||
type Rejection = (StatusCode, String);
|
||||
|
||||
async fn from_request(req: Request, state: &S) -> Result<Self, Self::Rejection> {
|
||||
let Json(payload) = Json::<UpdateRoomValues>::from_request(req, state)
|
||||
.await
|
||||
.map_err(|err| (StatusCode::BAD_REQUEST, format!("Invalid body: {}", err)))?;
|
||||
|
||||
Ok(UpdateRoomPayload(payload))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct RoomIdValue {
|
||||
pub room_id: i32
|
||||
}
|
||||
|
||||
pub type RoomIdPath = Path<i32>;
|
||||
79
src/rooms/handler.rs
Normal file
79
src/rooms/handler.rs
Normal file
@@ -0,0 +1,79 @@
|
||||
use axum::{Json, extract::Path, extract::State };
|
||||
use axum::response::IntoResponse;
|
||||
use axum::http::StatusCode;
|
||||
|
||||
use crate::rooms::extractor::UpdateRoomPayload;
|
||||
|
||||
use std::sync::Arc;
|
||||
use r2d2::{Pool};
|
||||
use r2d2_sqlite::SqliteConnectionManager;
|
||||
use dashmap::DashMap;
|
||||
use rusqlite::params;
|
||||
use crate::utils::db_pool::*;
|
||||
|
||||
|
||||
pub async fn hello_rooms() -> String {
|
||||
"hello from rooms".to_string()
|
||||
}
|
||||
|
||||
//fake handler
|
||||
pub async fn fake_room_update(
|
||||
Path(room_id): Path<i32>,
|
||||
UpdateRoomPayload(payload): UpdateRoomPayload
|
||||
) -> impl IntoResponse {
|
||||
|
||||
format!(
|
||||
"Got: token={}, status={}, room_id={}",
|
||||
payload.token, payload.status, room_id
|
||||
)
|
||||
}
|
||||
|
||||
pub async fn fake_db_update(
|
||||
|
||||
State(hotel_pools): State<HotelPools>,
|
||||
Path(room_id): Path<i32>,
|
||||
UpdateRoomPayload(payload): UpdateRoomPayload,
|
||||
|
||||
) -> impl IntoResponse {
|
||||
|
||||
let pool = hotel_pools.get_pool(payload.hotel_id);
|
||||
let conn = match pool.get() {
|
||||
Ok(conn) => conn,
|
||||
Err(err) => return (StatusCode::INTERNAL_SERVER_ERROR, format!("Pool error: {err}")),
|
||||
};
|
||||
|
||||
let result = conn.execute(
|
||||
"UPDATE rooms SET status = ?1 WHERE number = ?2",
|
||||
params![&payload.status, &room_id],
|
||||
);
|
||||
|
||||
|
||||
|
||||
match result {
|
||||
Ok(rows) if rows > 0 => (StatusCode::OK, format!("Updated room {room_id} in hotel {}", payload.hotel_id)),
|
||||
Ok(_) => (StatusCode::NOT_FOUND, "No room found".to_string()),
|
||||
Err(err) => (StatusCode::INTERNAL_SERVER_ERROR, format!("DB error: {err}")),
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
//fake db handler
|
||||
pub async fn update_room(UpdateRoomPayload(payload): UpdateRoom) -> impl IntoResponse {
|
||||
match fake_db_update(&payload.token, payload.room_id, &payload.status).await {
|
||||
Ok(msg) => msg,
|
||||
Err(err) => format!("Error: {}", err),
|
||||
}
|
||||
}
|
||||
|
||||
async fn fake_db_update(token: &str, room_id: i32, status: &str) -> Result<String, String> {
|
||||
// Pretend we check the token in the DB
|
||||
if token != "valid_token" {
|
||||
return Err("Invalid token".into());
|
||||
}
|
||||
|
||||
// Pretend we update the room status in the DB
|
||||
Ok(format!("Room {} updated to '{}'", room_id, status))
|
||||
}
|
||||
*/
|
||||
6
src/rooms/mod.rs
Normal file
6
src/rooms/mod.rs
Normal file
@@ -0,0 +1,6 @@
|
||||
//pub mod handler;
|
||||
//pub mod routes;
|
||||
|
||||
mod handler;
|
||||
mod extractor;
|
||||
pub mod routes;
|
||||
10
src/rooms/model.rs
Normal file
10
src/rooms/model.rs
Normal file
@@ -0,0 +1,10 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use uuid::Uuid;
|
||||
use chrono::{DateTime, Utc};
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, sqlx::FromRow)]
|
||||
pub struct Room{
|
||||
pub id: i32,
|
||||
pub room_number: i32,
|
||||
pub status: String
|
||||
}
|
||||
17
src/rooms/routes.rs
Normal file
17
src/rooms/routes.rs
Normal file
@@ -0,0 +1,17 @@
|
||||
use axum::{
|
||||
routing::{get, put,},
|
||||
Router,
|
||||
};
|
||||
|
||||
use crate::rooms::handler::*;
|
||||
use crate::utils::db_pool::HotelPools;
|
||||
|
||||
|
||||
// ROOTS
|
||||
pub fn rooms_routes() -> Router<HotelPools> {
|
||||
|
||||
Router::new()
|
||||
.route("/", get(hello_rooms) )
|
||||
.route("/fakeUpdate/{room_id}", put(fake_room_update))
|
||||
.route("/fake_db_update/{room_id}", put(fake_db_update))
|
||||
}
|
||||
@@ -2,11 +2,23 @@ use axum::{
|
||||
Router,
|
||||
};
|
||||
|
||||
pub mod rooms;
|
||||
pub mod inventory;
|
||||
use crate::rooms::routes::rooms_routes;
|
||||
|
||||
pub fn create_routes() -> Router {
|
||||
pub mod inventory;
|
||||
use crate::utils::db_pool::HotelPools;
|
||||
|
||||
pub fn create_router(hotel_pools: HotelPools) -> Router {
|
||||
Router::new()
|
||||
.nest("/inventory", inventory::inventory_routes())
|
||||
.nest("/rooms", rooms::rooms_routes())
|
||||
}
|
||||
.nest("/rooms", rooms_routes())
|
||||
.with_state(hotel_pools) // 👈 hotel_db is passed in as argument
|
||||
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
pub fn create_router() -> Router {
|
||||
Router::new()
|
||||
.nest("/rooms", rooms_routes())
|
||||
//.nest("/inventory", inventory::inventory_routes)
|
||||
}
|
||||
*/
|
||||
@@ -1,15 +0,0 @@
|
||||
use axum::{
|
||||
routing::{get, //post
|
||||
},
|
||||
Router,
|
||||
};
|
||||
|
||||
pub fn rooms_routes() -> Router {
|
||||
|
||||
Router::new()
|
||||
.route("/", get(hi_rooms) )
|
||||
}
|
||||
|
||||
async fn hi_rooms() -> &'static str {
|
||||
"Hiii from room.rs route module"
|
||||
}
|
||||
35
src/utils/db_pool.rs
Normal file
35
src/utils/db_pool.rs
Normal file
@@ -0,0 +1,35 @@
|
||||
use std::sync::Arc;
|
||||
use dashmap::DashMap;
|
||||
use r2d2::{Pool};
|
||||
use r2d2_sqlite::SqliteConnectionManager;
|
||||
|
||||
type HotelId = i32; // or i32 if you want numeric ids
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct HotelPools {
|
||||
pools: Arc<DashMap<HotelId, Pool<SqliteConnectionManager>>>,
|
||||
}
|
||||
|
||||
impl HotelPools {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
pools: Arc::new(DashMap::new()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get_pool(&self, hotel_id: i32) -> Pool<SqliteConnectionManager> {
|
||||
if let Some(pool) = self.pools.get(&hotel_id) {
|
||||
return pool.clone();
|
||||
}
|
||||
|
||||
let db_path = format!("db/{}.sqlite", hotel_id);
|
||||
let manager = SqliteConnectionManager::file(db_path);
|
||||
let pool = Pool::builder()
|
||||
.max_size(5) // adjust based on load
|
||||
.build(manager)
|
||||
.expect("Failed to build pool");
|
||||
|
||||
self.pools.insert(hotel_id, pool.clone());
|
||||
pool
|
||||
}
|
||||
}
|
||||
0
src/utils/dpPool.rs
Normal file
0
src/utils/dpPool.rs
Normal file
10
src/utils/hash.rs
Normal file
10
src/utils/hash.rs
Normal file
@@ -0,0 +1,10 @@
|
||||
use bcryp::{hash, verify, DEFAULT_COST};
|
||||
|
||||
pub fn bcrypt_hash(password: &str) -> Result<String, BcryptError> {
|
||||
hash(password, 5)
|
||||
}
|
||||
|
||||
pub fn bcrypt_verify(password: &str, hashed_password: &str) -> Result<String, BcryptError> {
|
||||
verify(password, hashed_password)
|
||||
}
|
||||
|
||||
1
src/utils/mod.rs
Normal file
1
src/utils/mod.rs
Normal file
@@ -0,0 +1 @@
|
||||
pub mod db_pool;
|
||||
44
src/utils/schema_extractor.rs
Normal file
44
src/utils/schema_extractor.rs
Normal file
@@ -0,0 +1,44 @@
|
||||
use axum::{
|
||||
async_traits,
|
||||
extract::FromRequestParts,
|
||||
http::request::Parts,
|
||||
};
|
||||
use jsonwebtoken::{decode, DecodingKey, Validation};
|
||||
use serde::Deserialize;
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct Claims {
|
||||
schema: String
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct UserSchema(pub String);
|
||||
|
||||
#[async_traits]
|
||||
impl<S> FromRequestParts<S> for UserSchema
|
||||
where
|
||||
S: Send + Sync,
|
||||
{
|
||||
type Rejection = axum::http::StatusCode;
|
||||
|
||||
async fn from_request_parts(
|
||||
parts: &mut Parts,
|
||||
_state: &S,
|
||||
) -> Reslult<Self, Self::Rejection> {
|
||||
let auth_header = parts
|
||||
.headers
|
||||
.get("authorizaton")
|
||||
.and_then(|h| h.to_str().ok())
|
||||
.ok_or(axum::http::StatusCode::UNAUTHORIZED)?;
|
||||
let token = auth_header.trim_start_matches("Bearer ");
|
||||
|
||||
let data = decode::<Claims>(
|
||||
token,
|
||||
&DecodingKey::from_secret("mysecret".as_ref()), // load from config later
|
||||
&Validation::default(),
|
||||
)
|
||||
.map_err(|_| axum::http::StatusCode::UNAUTHORIZED)?;
|
||||
|
||||
Ok(TenantSchema(data.claims.schema))
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user