ResourceHub API. Not for production. Changes in repository, not implemented sqlite, chages sensor data dto, Changes in Readme file, for update Concept for global collecting sensor's data from cities
This commit is contained in:
@@ -5,7 +5,7 @@ use rocket::{get, post};
|
||||
use crate::models::sensors::SensorData;
|
||||
use crate::models::sensors::get_sensor_data;
|
||||
|
||||
// use repository::Redis::
|
||||
use crate::repository::remote::redis;
|
||||
|
||||
// get data json obj
|
||||
// database.getSensorData()
|
||||
@@ -13,7 +13,7 @@ use crate::models::sensors::get_sensor_data;
|
||||
// 500
|
||||
// create data json obj
|
||||
// database.create(obj)
|
||||
// send 200 http response with json obj
|
||||
// send 200 http response
|
||||
// 500
|
||||
|
||||
#[post("/sensors/data", format="json", data="<json>")]
|
||||
@@ -25,35 +25,24 @@ pub async fn create(json: Json<SensorData>) -> status::Accepted<Json<SensorData>
|
||||
|
||||
// saved_data = database.create(data);
|
||||
// status::Accepted(Json(saved_data))
|
||||
|
||||
}
|
||||
|
||||
#[get("/sensors/data")]
|
||||
pub async fn get() -> status::Accepted<Json<SensorData>> {
|
||||
// get all data from DB
|
||||
let data = get_sensor_data();
|
||||
|
||||
let data = SensorData {
|
||||
id: Some(1),
|
||||
name: String::from("Sensor name"),
|
||||
value: 4.5,
|
||||
unit: String::from("C")
|
||||
};
|
||||
status::Accepted(Json(data))
|
||||
}
|
||||
|
||||
#[get("/sensors/data/<id>")]
|
||||
pub async fn get_by_id(id: u32) -> status::Accepted<Json<SensorData>> {
|
||||
// Vulnirability: danger if ID in sql requsets
|
||||
// http://127.0.0.1:8000/api/v1/sensors/data/?query=SELECT%20id%20FROM%20sensors
|
||||
// #[get("/sensors/data/<id>")]
|
||||
// pub async fn get_by_id(id: u32) -> status::Accepted<Json<SensorData>> {
|
||||
// // Vulnirability: danger if ID in sql requsets
|
||||
// // http://127.0.0.1:8000/api/v1/sensors/data/?query=SELECT%20id%20FROM%20sensors
|
||||
|
||||
// get data from DB
|
||||
// // get data from DB
|
||||
// let data = get_sensor_data();
|
||||
|
||||
let data: SensorData = SensorData {
|
||||
id: Some(id),
|
||||
name: String::from("Sensor name"),
|
||||
value: 4.5,
|
||||
unit: String::from("PH")
|
||||
};
|
||||
status::Accepted(Json(data))
|
||||
}
|
||||
// status::Accepted(Json(data))
|
||||
// }
|
||||
|
||||
|
||||
@@ -1,32 +1,14 @@
|
||||
mod util;
|
||||
mod endpoints;
|
||||
mod models;
|
||||
mod repository;
|
||||
|
||||
use rocket::{routes};
|
||||
use util::constants;
|
||||
use util::debug;
|
||||
use repository::remote::redis;
|
||||
|
||||
|
||||
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"));
|
||||
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[rocket::main]
|
||||
async fn main() -> Result<(), rocket::Error> {
|
||||
util::colored_text::print_colored_text_brand("> SocioCybereeng ");
|
||||
@@ -37,35 +19,33 @@ pub fn connect() -> redis::RedisResult<()> {
|
||||
debug::print_debug_info();
|
||||
}
|
||||
|
||||
// Get database pool
|
||||
// let pool = redis::get_pool(constants::DB_URI).await;
|
||||
|
||||
|
||||
// let DBconnector = ;
|
||||
|
||||
// Attempt to connect to DB and check the result
|
||||
let conection = connect();
|
||||
match conection {
|
||||
// match DBconnector::connect() {
|
||||
|
||||
Ok(conection) => {
|
||||
// Ok(conection) => {
|
||||
// If the connection is successful, store it or use it as needed
|
||||
let mut _db = conection;
|
||||
// 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?;
|
||||
// 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);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
// },
|
||||
// Err(err) => {
|
||||
// // Handle connection error and stop execution
|
||||
// std::process::exit(1);
|
||||
// }
|
||||
// }
|
||||
|
||||
}
|
||||
|
||||
@@ -1,22 +1,38 @@
|
||||
|
||||
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(Deserialize, Serialize)]
|
||||
#[serde(crate = "rocket::serde")]
|
||||
#[derive(Debug)]
|
||||
pub struct SensorData {
|
||||
pub id: Option<u32>,
|
||||
pub name: String,
|
||||
pub city_codename_cords_sector_cell: String, // CERCELL::[S1:C1]
|
||||
pub sensor_name_and_model: String,
|
||||
pub value: f32,
|
||||
pub unit: String,
|
||||
pub timestamp: u32
|
||||
}
|
||||
|
||||
// #[derive(Debug)]
|
||||
pub fn get_sensor_data() -> SensorData {
|
||||
SensorData {
|
||||
id: Some(1),
|
||||
name: String::from("Sensor name"),
|
||||
value: 4.5,
|
||||
unit: String::from("C")
|
||||
city_codename_cords_sector_cell: String::from("CERCELL:[40.7128,-74.0060]::S1:C1"),
|
||||
sensor_name_and_model: String::from("Humidity:[DHT22]"),
|
||||
value: 20.7,
|
||||
unit: String::from("RH"),
|
||||
timestamp: 17000002
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -1,6 +0,0 @@
|
||||
// use redis::AsyncCommands;
|
||||
// ! Load REDIS_PORT from env
|
||||
|
||||
// pub mod DBConnector {
|
||||
|
||||
// }
|
||||
2
ResourceHub/src/repository/mod.rs
Normal file
2
ResourceHub/src/repository/mod.rs
Normal file
@@ -0,0 +1,2 @@
|
||||
pub mod remote;
|
||||
// pub mod local;
|
||||
2
ResourceHub/src/repository/remote/mod.rs
Normal file
2
ResourceHub/src/repository/remote/mod.rs
Normal file
@@ -0,0 +1,2 @@
|
||||
pub mod redis;
|
||||
// pub mod postgres;
|
||||
@@ -1,2 +1,85 @@
|
||||
redis
|
||||
postgresql
|
||||
// use tokio::sync::{OnceCell, Mutex};
|
||||
// use redis::{Connection, ConnectionLike, JsonCommands, RedisResult};
|
||||
// use rocket::serde::{Deserialize, Serialize};
|
||||
|
||||
|
||||
// static DB_POOL: OnceCell<redis::Client> = OnceCell::const_new();
|
||||
// static DB_CONNECTOR: OnceCell<Mutex<Connection>> = OnceCell::const_new();
|
||||
|
||||
// pub async fn get_pool(URI: &str) -> &'static redis::Client {
|
||||
// DB_POOL.get_or_init(|| async {
|
||||
// redis::Client::open(URI).expect("[ERR] Can't connect to database.")
|
||||
// }).await
|
||||
// }
|
||||
|
||||
|
||||
// // Async‑compatible accessor
|
||||
// pub async fn get_conn() -> tokio::sync::MutexGuard<'static, Connection> {
|
||||
// DB_CONNECTOR
|
||||
// .get()
|
||||
// .expect("Redis not initialised")
|
||||
// .lock()
|
||||
// .await
|
||||
// }
|
||||
|
||||
|
||||
// pub async fn get_data<T>(key: &str, con: &mut Connection) -> RedisResult<(T)>
|
||||
// where T: Deserialize<'static> {
|
||||
// let raw_data: String = con.json_get(&key, ".")?;
|
||||
// Ok( serde_json::from_str(&raw_data)? )
|
||||
// }
|
||||
|
||||
// pub async fn set_data<T>(key: &str, data: &T, con: &mut Connection) -> RedisResult<()>
|
||||
// where T: Serialize,
|
||||
// {
|
||||
// Ok( con.json_set(&key, "$", &data)? )
|
||||
// }
|
||||
|
||||
use tokio::sync::OnceCell;
|
||||
use tokio::sync::Mutex;
|
||||
use redis::{Client, Connection};
|
||||
|
||||
static DB_POOL: OnceCell<Client> = OnceCell::const_new();
|
||||
static DB_CONNECTOR: OnceCell<Mutex<Connection>> = OnceCell::const_new();
|
||||
|
||||
pub async fn get_pool(uri: &str) -> redis::RedisResult<()> {
|
||||
let client = Client::open(uri)?;
|
||||
DB_POOL.set(client).ok();
|
||||
|
||||
let conn = DB_POOL
|
||||
.get()
|
||||
.unwrap()
|
||||
.get_connection()
|
||||
?;
|
||||
DB_CONNECTOR.set(Mutex::new(conn)).ok();
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// Async‑compatible accessor
|
||||
pub async fn get_conn() -> tokio::sync::MutexGuard<'static, Connection> {
|
||||
DB_CONNECTOR
|
||||
.get()
|
||||
.expect("Redis not initialised")
|
||||
.lock()
|
||||
.await
|
||||
}
|
||||
|
||||
// TODO TOKIIO AND MUTEX
|
||||
|
||||
// async fn test<RV>() -> RedisResult<()> {
|
||||
// let _pool = redis::get_pool(constants::DB_URI).await;
|
||||
// let mut con = redis::get_conn();
|
||||
|
||||
// let data1 = SensorData {
|
||||
// id: Some(1),
|
||||
// city_codename_cords_sector_cell: String::from("CERCELL:[40.7128,-74.0060]::S1:C1"),
|
||||
// sensor_name_and_model: String::from("Humidity:[DHT22]"),
|
||||
// value: 20.7,
|
||||
// unit: String::from("RH"),
|
||||
// timestamp: 17000002
|
||||
// };
|
||||
|
||||
// con.son_set::<&str, &str, SensorData, RV>("asd", "$", &data1);
|
||||
// Ok(())
|
||||
// }
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
pub const IS_DEBUG: bool = true; // set to 'false' in production!
|
||||
pub const API_VERSION: &str = "1";
|
||||
pub const DB_NAME: &str = "Redis";
|
||||
pub const DB_URL: &str = "redis://127.0.0.1:7878";
|
||||
pub const DB_URI: &str = "redis://:fswerfds@127.0.0.1:7878/";
|
||||
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
pub mod constants;
|
||||
pub mod colored_text;
|
||||
pub mod debug;
|
||||
pub mod debug;
|
||||
|
||||
Reference in New Issue
Block a user