ResourceHub API. Not for production. Code slitted into fucntional Modules

This commit is contained in:
SocioCyber
2026-03-17 00:40:16 -07:00
parent 8a4b324832
commit 21d0a0dd07
18 changed files with 175 additions and 270 deletions

View File

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

View File

@@ -1,18 +1,12 @@
// use database
use rocket::serde::{Deserialize, Serialize, json::Json};
use rocket::serde::{json::Json};
use rocket::response::status;
use rocket::{get, post};
#[derive(Deserialize, Serialize)]
#[serde(crate = "rocket::serde")]
pub struct SensorData {
id: Option<u32>,
name: String,
value: f32,
unit: String,
}
use crate::models::sensors::SensorData;
use crate::models::sensors::get_sensor_data;
// use repository::Redis::
// get data json obj
// database.getSensorData()
// send 200 http response with json obj
@@ -26,16 +20,10 @@ pub struct SensorData {
pub async fn create(json: Json<SensorData>) -> status::Accepted<Json<SensorData>> {
let received_data = json.into_inner();
let data = SensorData {
id: None,
name: String::from(received_data.name),
value: received_data.value,
unit: received_data.unit
};
let data = get_sensor_data();
status::Accepted(Json(data))
// saved_data = database.create(data);
// status::Accepted(Json(saved_data))
}

View File

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

View File

@@ -1,22 +1,31 @@
mod util;
mod endpoints;
mod models;
use rocket::{routes};
use crate::util::constants;
use util::constants;
use util::debug;
mod util {
pub mod constants;
pub mod colored_text;
}
pub fn connect() -> redis::RedisResult<()> {
let client = redis::Client::open("redis://127.0.0.1:7878/")?;
let mut connector = client.get_connection()?;
// let mut connector = client.get_connection();
// connector.set("Name", "Redis");
// println!("DB name:: {}", connector.get("Name"));
mod endpoints {
pub mod sensors {
pub mod data;
match client.get_connection() {
Ok(mut connector) => {
util::colored_text::print_colored_text_info("[DB] Connected ");
Ok(())
},
Err(e) => {
util::colored_text::print_colored_text_err("[DB] Error, check redis database is running? (./Database/run.sh) Fix REDIS_PORT if not correctly setted;\n[Wiki] Instructions: https://git.sociocyber.site:5000/SocioCybereeng/Hydroponic_systems/src/branch/master/ResourceHub/Readme.md ", e.to_string());
Err(e)
}
}
}
fn print_debug_info() {
util::colored_text::print_colored_text_info(&format!("- SERVER INFO:"));
util::colored_text::print_colored_text_info(&format!(" - API VERSION: {} ", constants::API_VERSION));
util::colored_text::print_colored_text_info(&format!(" - DB NAME: {} ", constants::DB_NAME));
}
#[rocket::main]
async fn main() -> Result<(), rocket::Error> {
@@ -25,48 +34,38 @@ fn print_debug_info() {
util::colored_text::print_colored_text_info("- [Welcome to ResourceHUB API] ");
if util::constants::IS_DEBUG == true {
print_debug_info();
debug::print_debug_info();
}
// let mut status = ServerStatus::Online;
// // Use the colored printing function based on the server status
// match status {
// ServerStatus::Online => {
// }
// ServerStatus::Offline => {
// util::colored_text::print_colored_text_notify("[SERVER_STATUS] The server is stopped.");
// }
// ServerStatus::Starting => {
// util::colored_text::print_colored_text_notify("[SERVER_STATUS] The server is starting.");
// }
// ServerStatus::Stopping => {
// util::colored_text::print_colored_text_notify("[SERVER_STATUS] The server is stopping.");
// }
// ServerStatus::Error(ref err) => {
// util::colored_text::print_colored_text_err(&format!("[SERVER_STATUS] An error occurred: {}", err));
// }
// }
// let DBconnector = ;
// Attempt to connect to DB and check the result
let conection = connect();
match conection {
// match DBconnector::connect() {
// Start server
let _rocket = rocket::build()
.mount(format!("/api/v{}/", constants::API_VERSION), routes![
endpoints::sensors::data::create,
endpoints::sensors::data::get,
endpoints::sensors::data::get_by_id,
])
.launch()
.await?;
Ok(())
Ok(conection) => {
// If the connection is successful, store it or use it as needed
let mut _db = conection;
// Start server
let _rocket = rocket::build()
.mount(format!("/api/v{}/", constants::API_VERSION), routes![
endpoints::sensors::data::create,
endpoints::sensors::data::get,
endpoints::sensors::data::get_by_id,
])
.launch()
.await?;
Ok(())
},
Err(err) => {
// Handle connection error and stop execution
std::process::exit(1);
}
}
}
// #[macro_use] extern crate rocket;
// #[launch]
// fn rocket() -> _ {
// Create an instance of ServerStatus

View File

@@ -0,0 +1,6 @@
pub mod sensors;
// pub mod something_data;
// pub mod something_data;
// pub mod something_data;
// pub mod something_data;
// pub mod something_data;

View File

@@ -0,0 +1,22 @@
use rocket::serde::{Deserialize, Serialize};
#[derive(Deserialize, Serialize)]
#[serde(crate = "rocket::serde")]
#[derive(Debug)]
pub struct SensorData {
pub id: Option<u32>,
pub name: String,
pub value: f32,
pub unit: String,
}
// #[derive(Debug)]
pub fn get_sensor_data() -> SensorData {
SensorData {
id: Some(1),
name: String::from("Sensor name"),
value: 4.5,
unit: String::from("C")
}
}

View File

@@ -0,0 +1,6 @@
// use redis::AsyncCommands;
// ! Load REDIS_PORT from env
// pub mod DBConnector {
// }

View File

@@ -1,94 +0,0 @@
// DBconnector
mod DBconnector {
use redis::AsyncCommands;
async fn run() {
let mut r = match redis::Client::open("redis://127.0.0.1:7878") {
Ok(client) => {
match client.get_multiplexed_async_connection().await {
Ok(conn) => conn,
Err(e) => {
println!("Failed to connect to Redis: {e}");
return;
}
}
},
Err(e) => {
println!("Failed to create Redis client: {e}");
return;
}
};
if let Ok(res) = r.set("foo", "bar").await {
let res: String = res;
println!("{res}"); // >>> OK
} else {
println!("Error setting foo");
}
match r.get("foo").await {
Ok(res) => {
let res: String = res;
println!("{res}"); // >>> bar
},
Err(e) => {
println!("Error getting foo: {e}");
return;
}
};
let hash_fields = [
("model", "Deimos"),
("brand", "Ergonom"),
("type", "Enduro bikes"),
("price", "4972"),
];
if let Ok(res) = r.hset_multiple("bike:1", &hash_fields).await {
let res: String = res;
println!("{res}"); // >>> OK
} else {
println!("Error setting bike:1");
}
match r.hget("bike:1", "model").await {
Ok(res) => {
let res: String = res;
println!("{res}"); // >>> Deimos
},
Err(e) => {
println!("Error getting bike:1 model: {e}");
return;
}
}
match r.hget("bike:1", "price").await {
Ok(res) => {
let res: String = res;
println!("{res}"); // >>> 4972
},
Err(e) => {
println!("Error getting bike:1 price: {e}");
return;
}
}
match r.hgetall("bike:1").await {
Ok(res) => {
let res: Vec<(String, String)> = res;
for (key, value) in res {
println!("{key}: {value}");
}
// >>> model: Deimos
// >>> brand: Ergonom
// >>> type: Enduro bikes
// >>> price: 4972
},
Err(e) => {
println!("Error getting bike:1: {e}");
return;
}
}
}
}

View File

@@ -0,0 +1 @@
sqlite

View File

@@ -0,0 +1,2 @@
redis
postgresql

View File

@@ -13,12 +13,16 @@ pub fn print_colored_text_info(string: &str) {
// );
// }
// pub fn print_colored_text_err(string: &str) {
// println!("{}", string
// .color(Color::RED)
// .bg(Color::BLACK)
// );
// }
pub fn print_colored_text_err(string: &str, error_message: String) {
println!("{}", string
.color(Color::RED)
.bg(Color::BLACK)
);
println!("{}", error_message
.color(Color::RED)
.bg(Color::BLACK)
);
}
pub fn print_colored_text_brand(string: &str) {
println!("{}", string

View File

@@ -0,0 +1,8 @@
use crate::constants;
use crate::util::colored_text::*;
pub fn print_debug_info() {
print_colored_text_info(&format!("- SERVER INFO:"));
print_colored_text_info(&format!(" - API VERSION: {} ", constants::API_VERSION));
print_colored_text_info(&format!(" - DB NAME: {} ", constants::DB_NAME));
}

View File

@@ -0,0 +1,3 @@
pub mod constants;
pub mod colored_text;
pub mod debug;