ResourceHub API. Not for production. Get/Post, Json Serialize/Deserialize
This commit is contained in:
71
ResourceHub/src/endpoints/sensors/data.rs
Normal file
71
ResourceHub/src/endpoints/sensors/data.rs
Normal file
@@ -0,0 +1,71 @@
|
||||
// use database
|
||||
use rocket::serde::{Deserialize, Serialize, 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,
|
||||
}
|
||||
// get data json obj
|
||||
// database.getSensorData()
|
||||
// send 200 http response with json obj
|
||||
// 500
|
||||
// create data json obj
|
||||
// database.create(obj)
|
||||
// send 200 http response with json obj
|
||||
// 500
|
||||
|
||||
#[post("/sensors/data", format="json", data="<json>")]
|
||||
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
|
||||
};
|
||||
status::Accepted(Json(data))
|
||||
|
||||
// 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 = 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 data from DB
|
||||
|
||||
let data: SensorData = SensorData {
|
||||
id: Some(id),
|
||||
name: String::from("Sensor name"),
|
||||
value: 4.5,
|
||||
unit: String::from("PH")
|
||||
};
|
||||
status::Accepted(Json(data))
|
||||
}
|
||||
|
||||
72
ResourceHub/src/main.rs
Normal file
72
ResourceHub/src/main.rs
Normal file
@@ -0,0 +1,72 @@
|
||||
use rocket::{routes};
|
||||
use crate::util::constants;
|
||||
|
||||
|
||||
mod util {
|
||||
pub mod constants;
|
||||
pub mod colored_text;
|
||||
}
|
||||
|
||||
mod endpoints {
|
||||
pub mod sensors {
|
||||
pub mod data;
|
||||
}
|
||||
}
|
||||
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> {
|
||||
util::colored_text::print_colored_text_brand("> SocioCybereeng ");
|
||||
util::colored_text::print_colored_text_project("> Project: Hydroponic Systems ");
|
||||
util::colored_text::print_colored_text_info("- [Welcome to ResourceHUB API] ");
|
||||
|
||||
if util::constants::IS_DEBUG == true {
|
||||
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));
|
||||
// }
|
||||
// }
|
||||
|
||||
// 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(())
|
||||
}
|
||||
|
||||
|
||||
// #[macro_use] extern crate rocket;
|
||||
// #[launch]
|
||||
// fn rocket() -> _ {
|
||||
|
||||
// Create an instance of ServerStatus
|
||||
|
||||
|
||||
|
||||
|
||||
0
ResourceHub/src/model/SensorData.rs
Normal file
0
ResourceHub/src/model/SensorData.rs
Normal file
94
ResourceHub/src/repository/Database.rs
Normal file
94
ResourceHub/src/repository/Database.rs
Normal file
@@ -0,0 +1,94 @@
|
||||
// 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
43
ResourceHub/src/util/colored_text.rs
Normal file
43
ResourceHub/src/util/colored_text.rs
Normal file
@@ -0,0 +1,43 @@
|
||||
use tinterm::*;
|
||||
|
||||
pub fn print_colored_text_info(string: &str) {
|
||||
println!("{}", string
|
||||
.gradient(Color::LIGHT_CYAN, Color::LIME_GREEN, None)
|
||||
.bg(Color::BLACK));
|
||||
}
|
||||
|
||||
// pub fn print_colored_text_notify(string: &str) {
|
||||
// println!("{}", string
|
||||
// .color(Color::LIGHT_GREEN)
|
||||
// .bg(Color::BLACK)
|
||||
// );
|
||||
// }
|
||||
|
||||
// pub fn print_colored_text_err(string: &str) {
|
||||
// println!("{}", string
|
||||
// .color(Color::RED)
|
||||
// .bg(Color::BLACK)
|
||||
// );
|
||||
// }
|
||||
|
||||
pub fn print_colored_text_brand(string: &str) {
|
||||
println!("{}", string
|
||||
.gradient(Color::LIGHT_CYAN, Color::DEEP_SKY_BLUE, None)
|
||||
.bg(Color::BLACK));
|
||||
}
|
||||
// pub fn show_progress(percent: usize) {
|
||||
// let filled = "█".repeat(percent / 5);
|
||||
// let empty = "░".repeat(20 - percent / 5);
|
||||
//
|
||||
// println!("Progress: [{}{}] {}%",
|
||||
// filled.color(Color::LIGHT_CYAN),
|
||||
// empty.color(Color::DARK_GRAY),
|
||||
// percent
|
||||
// );
|
||||
// }
|
||||
|
||||
pub fn print_colored_text_project(string: &str) {
|
||||
println!("{}", string
|
||||
.gradient(Color::LIGHT_CYAN, Color::CHARTREUSE, None)
|
||||
.bg(Color::BLACK));
|
||||
}
|
||||
5
ResourceHub/src/util/constants.rs
Normal file
5
ResourceHub/src/util/constants.rs
Normal file
@@ -0,0 +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";
|
||||
|
||||
Reference in New Issue
Block a user