Working on rust backend
This commit is contained in:
5
backend/src/airports/mod.rs
Normal file
5
backend/src/airports/mod.rs
Normal file
@@ -0,0 +1,5 @@
|
||||
mod model;
|
||||
mod routes;
|
||||
|
||||
pub use model::*;
|
||||
pub use routes::init_routes;
|
||||
31
backend/src/airports/model.rs
Normal file
31
backend/src/airports/model.rs
Normal file
@@ -0,0 +1,31 @@
|
||||
use crate::db;
|
||||
use crate::error_handler::CustomError;
|
||||
use crate::schema::airports;
|
||||
use diesel::prelude::*;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Serialize, Deserialize, AsChangeset, Insertable)]
|
||||
#[table_name = "airports"]
|
||||
pub struct Airport {
|
||||
pub name: String,
|
||||
pub icao: String,
|
||||
pub latitude: f32,
|
||||
pub longitude: f32,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Queryable)]
|
||||
pub struct Airports {
|
||||
pub id: i32,
|
||||
pub name: String,
|
||||
pub icao: String,
|
||||
pub latitude: f32,
|
||||
pub longitude: f32,
|
||||
}
|
||||
|
||||
impl Airports {
|
||||
pub fn find_all() -> Result<Vec<Self>, CustomError> {
|
||||
let conn = db::connection()?;
|
||||
let airports = airports::table.load::<Airports>(&conn)?;
|
||||
Ok(airports)
|
||||
}
|
||||
}
|
||||
14
backend/src/airports/routes.rs
Normal file
14
backend/src/airports/routes.rs
Normal file
@@ -0,0 +1,14 @@
|
||||
use crate::airports::{Airport, Airports};
|
||||
use crate::error_handler::CustomError;
|
||||
use actix_web::{delete, get, post, put, web, HttpResponse};
|
||||
use serde_json::json;
|
||||
|
||||
#[get("/airports")]
|
||||
async fn find_all() -> Result<HttpResponse, CustomError> {
|
||||
let airports = web::block(|| Airports::find_all()).await.unwrap();
|
||||
Ok(HttpResponse::Ok().json(airports))
|
||||
}
|
||||
|
||||
pub fn init_routes(config: &mut web::ServiceConfig) {
|
||||
config.service(find_all);
|
||||
}
|
||||
30
backend/src/db.rs
Normal file
30
backend/src/db.rs
Normal file
@@ -0,0 +1,30 @@
|
||||
use crate::error_handler::CustomError;
|
||||
use diesel::pg::PgConnection;
|
||||
use diesel::r2d2::ConnectionManager;
|
||||
use lazy_static::lazy_static;
|
||||
use r2d2;
|
||||
use std::env;
|
||||
|
||||
type Pool = r2d2::Pool<ConnectionManager<PgConnection>>;
|
||||
pub type DbConnection = r2d2::PooledConnection<ConnectionManager<PgConnection>>;
|
||||
|
||||
embed_migrations!();
|
||||
|
||||
lazy_static! {
|
||||
static ref POOL: Pool = {
|
||||
let db_url = env::var("DATABASE_URL").expect("Database url not set");
|
||||
let manager = ConnectionManager::<PgConnection>::new(db_url);
|
||||
Pool::new(manager).expect("Failed to create db pool")
|
||||
};
|
||||
}
|
||||
|
||||
pub fn init() {
|
||||
lazy_static::initialize(&POOL);
|
||||
let conn = connection().expect("Failed to get db connection");
|
||||
embedded_migrations::run(&conn).unwrap();
|
||||
}
|
||||
|
||||
pub fn connection() -> Result<DbConnection, CustomError> {
|
||||
POOL.get()
|
||||
.map_err(|e| CustomError::new(500, format!("Failed getting db connection: {}", e)))
|
||||
}
|
||||
55
backend/src/error_handler.rs
Normal file
55
backend/src/error_handler.rs
Normal file
@@ -0,0 +1,55 @@
|
||||
use actix_web::http::StatusCode;
|
||||
use actix_web::{HttpResponse, ResponseError};
|
||||
use diesel::result::Error as DieselError;
|
||||
use serde::Deserialize;
|
||||
use serde_json::json;
|
||||
use std::fmt;
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct CustomError {
|
||||
pub error_status_code: u16,
|
||||
pub error_message: String,
|
||||
}
|
||||
|
||||
impl CustomError {
|
||||
pub fn new(error_status_code: u16, error_message: String) -> CustomError {
|
||||
CustomError {
|
||||
error_status_code,
|
||||
error_message,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for CustomError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
f.write_str(self.error_message.as_str())
|
||||
}
|
||||
}
|
||||
|
||||
impl From<DieselError> for CustomError {
|
||||
fn from(error: DieselError) -> CustomError {
|
||||
match error {
|
||||
DieselError::DatabaseError(_, err) => CustomError::new(409, err.message().to_string()),
|
||||
DieselError::NotFound => {
|
||||
CustomError::new(404, "The employee record not found".to_string())
|
||||
}
|
||||
err => CustomError::new(500, format!("Unknown Diesel error: {}", err)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ResponseError for CustomError {
|
||||
fn error_response(&self) -> HttpResponse {
|
||||
let status_code = match StatusCode::from_u16(self.error_status_code) {
|
||||
Ok(status_code) => status_code,
|
||||
Err(_) => StatusCode::INTERNAL_SERVER_ERROR,
|
||||
};
|
||||
|
||||
let error_message = match status_code.as_u16() < 500 {
|
||||
true => self.error_message.clone(),
|
||||
false => "Internal server error".to_string(),
|
||||
};
|
||||
|
||||
HttpResponse::build(status_code).json(json!({ "message": error_message }))
|
||||
}
|
||||
}
|
||||
162
backend/src/lib.rs.bk
Normal file
162
backend/src/lib.rs.bk
Normal file
@@ -0,0 +1,162 @@
|
||||
use std::error::Error;
|
||||
use std::fmt;
|
||||
use log::warn;
|
||||
use std::io::BufRead;
|
||||
use quick_xml::{Reader, events::{Event, BytesStart}, Writer, de::Deserializer};
|
||||
use serde::Deserialize;
|
||||
|
||||
pub struct Airport {
|
||||
pub name: String,
|
||||
pub icao: String
|
||||
}
|
||||
|
||||
impl Airport {
|
||||
pub fn new(name: String, icao: String) -> Airport {
|
||||
Airport { name, icao }
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct WeatherError(pub String);
|
||||
|
||||
impl fmt::Display for WeatherError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
write!(f, "{}", self.0)
|
||||
}
|
||||
}
|
||||
|
||||
impl Error for WeatherError {}
|
||||
|
||||
#[derive(Deserialize, Debug)]
|
||||
pub struct Metar {
|
||||
pub raw_text: String,
|
||||
pub station_id: String,
|
||||
pub observation_time: String,
|
||||
pub latitude: f32,
|
||||
pub longitude: f32,
|
||||
pub temp_c: f32,
|
||||
pub dewpoint_c: f32,
|
||||
pub wind_dir_degrees: i32,
|
||||
pub wind_speed_kt: i32,
|
||||
pub visibility_statute_mi: String,
|
||||
pub altim_in_hg: f32,
|
||||
pub sea_level_pressure_mb: Option<f32>,
|
||||
pub quality_control_flags: Option<QualityControlFlags>,
|
||||
pub wx_string: Option<String>,
|
||||
// pub sky_con dition: Option<Vec<String>>, // TODO work on attributes
|
||||
pub flight_category: String,
|
||||
pub three_hr_pressure_tendency_mb: Option<f32>,
|
||||
pub metar_type: String,
|
||||
#[serde(rename = "maxT_c")]
|
||||
pub max_t_c: Option<f32>,
|
||||
#[serde(rename = "minT_c")]
|
||||
pub min_t_c: Option<f32>,
|
||||
pub precip_in: Option<f32>,
|
||||
pub elevation_m: i32
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Debug)]
|
||||
pub struct QualityControlFlags {
|
||||
pub auto: Option<bool>,
|
||||
pub auto_station: Option<bool>
|
||||
}
|
||||
|
||||
impl Metar {
|
||||
pub fn parse(input: String) -> Result<Vec<Metar>, WeatherError> {
|
||||
if input.is_empty() {
|
||||
return Err(WeatherError("Input is empty".to_string()))
|
||||
}
|
||||
|
||||
let mut reader = Reader::from_str(&input);
|
||||
let mut buf = Vec::new();
|
||||
let mut junk_buf: Vec<u8> = Vec::new();
|
||||
|
||||
loop {
|
||||
match reader.read_event_into(&mut buf) {
|
||||
Err(e) => panic!("Error at position: {}: {:?}", reader.buffer_position(), e),
|
||||
Ok(Event::Eof) => break,
|
||||
Ok(Event::Start(e)) => {
|
||||
match e.name().as_ref() {
|
||||
b"METAR" => {
|
||||
let metar_bytes = Metar::read_to_end_into_buffer(&mut reader, &e, &mut junk_buf).unwrap();
|
||||
let str = std::str::from_utf8(&metar_bytes).unwrap();
|
||||
let mut deserializer = Deserializer::from_str(str);
|
||||
let metar = Metar::deserialize(&mut deserializer).unwrap();
|
||||
println!("{:#?}", metar);
|
||||
},
|
||||
_ => ()
|
||||
}
|
||||
},
|
||||
_ => ()
|
||||
}
|
||||
}
|
||||
|
||||
return Ok(vec![])
|
||||
}
|
||||
|
||||
// https://capnfabs.net/posts/parsing-huge-xml-quickxml-rust-serde/
|
||||
pub fn read_to_end_into_buffer<R: BufRead>(reader: &mut Reader<R>, start_tag: &BytesStart, junk_buf: &mut Vec<u8>) -> Result<Vec<u8>, quick_xml::Error> {
|
||||
let mut depth = 0;
|
||||
let mut output_buf: Vec<u8> = Vec::new();
|
||||
let mut w = Writer::new(&mut output_buf);
|
||||
let tag_name = start_tag.name();
|
||||
w.write_event(Event::Start(start_tag.clone()))?;
|
||||
loop {
|
||||
junk_buf.clear();
|
||||
let event = reader.read_event_into(junk_buf)?;
|
||||
w.write_event(&event)?;
|
||||
|
||||
match event {
|
||||
Event::Start(e) if e.name() == tag_name => depth += 1,
|
||||
Event::End(e) if e.name() == tag_name => {
|
||||
if depth == 0 {
|
||||
return Ok(output_buf);
|
||||
}
|
||||
depth -= 1;
|
||||
}
|
||||
Event::Eof => {
|
||||
panic!("EOF")
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Weather {
|
||||
pub base_url: String
|
||||
}
|
||||
|
||||
impl Weather {
|
||||
pub async fn metar(&mut self, airports: Vec<Airport>) -> Vec<Metar> {
|
||||
let mut station_icaos: Vec<&str> = vec![];
|
||||
for station in airports.iter() {
|
||||
station_icaos.push(&station.icao);
|
||||
}
|
||||
let station_string = station_icaos.join(",");
|
||||
let url = format!("{}/metar.php?ids={}&format=xml", self.base_url, station_string);
|
||||
|
||||
let metars: Vec<Metar> = match reqwest::get(url).await {
|
||||
Ok(r) => match r.text().await {
|
||||
Ok(r) => {
|
||||
match Metar::parse(r) {
|
||||
Ok(m) => m,
|
||||
Err(err) => {
|
||||
warn!("{}", err);
|
||||
vec![]
|
||||
}
|
||||
}
|
||||
},
|
||||
Err(err) => {
|
||||
warn!("Unable to parse METAR request: {}", err);
|
||||
vec![]
|
||||
}
|
||||
},
|
||||
Err(err) => {
|
||||
warn!("Unable to get METAR request: {}", err);
|
||||
vec![]
|
||||
}
|
||||
};
|
||||
return metars;
|
||||
}
|
||||
}
|
||||
33
backend/src/main.rs
Normal file
33
backend/src/main.rs
Normal file
@@ -0,0 +1,33 @@
|
||||
#[macro_use]
|
||||
extern crate diesel;
|
||||
#[macro_use]
|
||||
extern crate diesel_migrations;
|
||||
|
||||
use actix_web::{App, HttpServer};
|
||||
use dotenv::dotenv;
|
||||
use listenfd::ListenFd;
|
||||
use std::env;
|
||||
|
||||
mod airports;
|
||||
mod db;
|
||||
mod error_handler;
|
||||
mod schema;
|
||||
|
||||
#[actix_rt::main]
|
||||
async fn main() -> std::io::Result<()> {
|
||||
dotenv().ok();
|
||||
db::init();
|
||||
|
||||
let mut listenfd = ListenFd::from_env();
|
||||
let mut server = HttpServer::new(|| App::new().configure(airports::init_routes));
|
||||
|
||||
server = match listenfd.take_tcp_listener(0)? {
|
||||
Some(listener) => server.listen(listener)?,
|
||||
None => {
|
||||
let host = env::var("HOST").expect("Please set host in .env");
|
||||
let port = env::var("PORT").expect("Please set port in .env");
|
||||
server.bind(format!("{}:{}", host, port))?
|
||||
}
|
||||
};
|
||||
server.run().await
|
||||
}
|
||||
9
backend/src/schema.rs
Normal file
9
backend/src/schema.rs
Normal file
@@ -0,0 +1,9 @@
|
||||
table! {
|
||||
airports (id) {
|
||||
id -> Int4,
|
||||
name -> Varchar,
|
||||
icao -> Varchar,
|
||||
latitude: Int4,
|
||||
longitude: Int4
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user