Refactor, fixed search

This commit is contained in:
2023-09-15 09:08:33 -04:00
parent 4114d533b2
commit 128181bed6
28 changed files with 343 additions and 342 deletions

View File

@@ -2,6 +2,7 @@ use crate::db;
use crate::error_handler::CustomError; use crate::error_handler::CustomError;
use crate::schema::airports; use crate::schema::airports;
use diesel::prelude::*; use diesel::prelude::*;
use log::trace;
use postgis_diesel::types::*; use postgis_diesel::types::*;
use postgis_diesel::functions::*; use postgis_diesel::functions::*;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
@@ -23,7 +24,8 @@ pub struct Airport {
pub point: Point pub point: Point
} }
#[derive(Serialize, Deserialize, Queryable)] #[derive(Serialize, Deserialize, Queryable, QueryableByName)]
#[diesel(table_name = airports)]
pub struct Airports { pub struct Airports {
pub icao: String, pub icao: String,
pub id: i32, pub id: i32,
@@ -41,32 +43,28 @@ pub struct Airports {
} }
impl Airports { impl Airports {
pub fn find_all(bounds: Option<Polygon<Point>>, category: Option<String>, limit: i32, page: i32) -> Result<Vec<Self>, CustomError> { pub fn get_all(bounds: Option<Polygon<Point>>, category: Option<String>, filter: Option<String>, limit: i32, page: i32) -> Result<Vec<Self>, CustomError> {
let mut conn = db::connection()?; let mut conn = db::connection()?;
let airports; let mut query = airports::table
.limit(limit as i64)
.into_boxed();
query = query.filter(airports::id.gt(page * limit));
if let Some(bounds) = bounds {
query = query.filter(st_contains(bounds, airports::point));
}
if let Some(category) = category { if let Some(category) = category {
airports = airports::table query = query.filter(airports::category.eq(category));
.limit(limit as i64)
.filter(airports::id.gt(page * limit).and(match bounds {
Some(b) => st_contains(b, airports::point),
None => {
let polygon: Polygon<Point> = Polygon::new(Some(4326));
st_contains(polygon, airports::point)
} }
}).and(airports::category.eq(category))).load::<Airports>(&mut conn)?; if let Some(filter) = filter {
} else { query = query.filter(airports::icao
airports = airports::table .ilike(format!("%{}%", filter))
.order(airports::category.asc()) .or(airports::full_name.ilike(format!("%{}%", filter)))
.limit(limit as i64) )
.filter(airports::id.gt(page * limit).and(match bounds {
Some(b) => st_contains(b, airports::point),
None => {
let polygon: Polygon<Point> = Polygon::new(Some(4326));
st_contains(polygon, airports::point)
}
}))
.load::<Airports>(&mut conn)?;
} }
let debug = diesel::debug_query::<diesel::pg::Pg, _>(&query);
trace!("{}", debug);
let airports: Vec<Airports> = query.order(airports::category.asc()).load::<Airports>(&mut conn)?;
Ok(airports) Ok(airports)
} }

View File

@@ -1,63 +1,115 @@
use crate::{airports::{Airport, Airports}, db}; use crate::{airports::{Airport, Airports}, db::{self, Metadata}};
use actix_web::{delete, get, post, put, web, HttpResponse, HttpRequest}; use actix_web::{delete, get, post, put, web, HttpResponse, HttpRequest};
use log::error; use log::{error, warn};
use postgis_diesel::types::{Polygon, Point}; use postgis_diesel::types::{Polygon, Point};
use serde::{Serialize, Deserialize}; use serde::{Serialize, Deserialize};
use serde_json::json;
#[derive(Debug, Serialize, Deserialize)] #[derive(Debug, Serialize, Deserialize)]
struct FindAllParams { struct GetAllParameters {
ne_lat: f64, filter: Option<String>,
ne_lon: f64, bounds: Option<String>,
sw_lat: f64,
sw_lon: f64,
category: Option<String>, category: Option<String>,
limit: i32, limit: i32,
page: i32 page: i32
} }
#[derive(Debug, Clone, Copy, Serialize, Deserialize)] #[get("/import")]
struct Coordinate { async fn import() -> HttpResponse {
lon: f64, db::import_data();
lat: f64 HttpResponse::Ok().body({})
} }
#[get("/setup")] #[derive(Serialize, Deserialize)]
async fn setup() -> HttpResponse { pub struct AirportsResponse {
db::import_data(); pub data: Vec<Airports>,
HttpResponse::Ok().finish() pub meta: Metadata
} }
#[get("/airports")] #[get("/airports")]
async fn find_all(req: HttpRequest) -> HttpResponse { async fn get_all(req: HttpRequest) -> HttpResponse {
let params = web::Query::<FindAllParams>::from_query(req.query_string()).unwrap(); let params = web::Query::<GetAllParameters>::from_query(req.query_string()).unwrap();
let polygon: Option<Polygon<Point>> = match &params.bounds {
Some(b) => {
let bounds: Vec<&str> = b.split(",").collect();
if bounds.len() != 4 {
warn!("Expected 4 bounds, received {}: {}", bounds.len(), b);
return HttpResponse::UnprocessableEntity().body(format!("Received {}; expected NE_LAT,NE_LON,SW_LAT,SW_LON", b))
}
let ne_lat = match bounds[0].parse::<f64>() {
Ok(b) => b,
Err(err) => {
warn!("{}", err);
return HttpResponse::UnprocessableEntity().body(format!("{}", err))
}
};
let ne_lon = match bounds[1].parse::<f64>() {
Ok(b) => b,
Err(err) => {
warn!("{}", err);
return HttpResponse::UnprocessableEntity().body(format!("{}", err))
}
};
let sw_lat = match bounds[2].parse::<f64>() {
Ok(b) => b,
Err(err) => {
warn!("{}", err);
return HttpResponse::UnprocessableEntity().body(format!("{}", err))
}
};
let sw_lon = match bounds[3].parse::<f64>() {
Ok(b) => b,
Err(err) => {
warn!("{}", err);
return HttpResponse::UnprocessableEntity().body(format!("{}", err))
}
};
let mut polygon: Polygon<Point> = Polygon::new(Some(4326)); let mut polygon: Polygon<Point> = Polygon::new(Some(4326));
polygon.add_point(Point { x: params.sw_lon, y: params.sw_lat, srid: Some(4326) }); polygon.add_point(Point { x: sw_lon, y: sw_lat, srid: Some(4326) });
polygon.add_point(Point { x: params.ne_lon, y: params.sw_lat, srid: Some(4326) }); polygon.add_point(Point { x: ne_lon, y: sw_lat, srid: Some(4326) });
polygon.add_point(Point { x: params.ne_lon, y: params.ne_lat, srid: Some(4326) }); polygon.add_point(Point { x: ne_lon, y: ne_lat, srid: Some(4326) });
polygon.add_point(Point { x: params.sw_lon, y: params.ne_lat, srid: Some(4326) }); polygon.add_point(Point { x: sw_lon, y: ne_lat, srid: Some(4326) });
polygon.add_point(Point { x: params.sw_lon, y: params.sw_lat, srid: Some(4326) }); polygon.add_point(Point { x: sw_lon, y: sw_lat, srid: Some(4326) });
Some(polygon)
},
None => None
};
let category = match &params.category { let category = match &params.category {
Some(c) => Some(c.to_string()), Some(c) => Some(c.to_string()),
None => None None => None
}; };
let filter = match &params.filter {
Some(f) => Some(f.to_string()),
None => None
};
match web::block(move || Airports::find_all(Some(polygon), category, params.limit, params.page)).await.unwrap() { match web::block(move || Airports::get_all(polygon, category, filter, params.limit, params.page)).await.unwrap() {
Ok(a) => HttpResponse::Ok().json(a), Ok(a) => HttpResponse::Ok().json(AirportsResponse {
data: a,
meta: Metadata { page: 0, limit: 0, pages: 0, total: 0 }
}),
Err(err) => { Err(err) => {
error!("{}", err); error!("{}", err);
HttpResponse::InternalServerError().finish() err.to_http_response()
} }
} }
} }
#[derive(Serialize, Deserialize)]
pub struct AirportResponse {
pub data: Airports,
pub meta: Metadata
}
#[get("/airports/{icao}")] #[get("/airports/{icao}")]
async fn find(icao: web::Path<String>) -> HttpResponse { async fn get(icao: web::Path<String>) -> HttpResponse {
match Airports::find(icao.into_inner()) { match Airports::find(icao.into_inner()) {
Ok(a) => HttpResponse::Ok().json(a), Ok(a) => HttpResponse::Ok().json(AirportResponse {
data: a,
meta: Metadata { page: 0, limit: 0, pages: 0, total: 0 }
}),
Err(err) => { Err(err) => {
error!("{}", err); error!("{}", err);
HttpResponse::InternalServerError().finish() err.to_http_response()
} }
} }
} }
@@ -65,10 +117,10 @@ async fn find(icao: web::Path<String>) -> HttpResponse {
#[post("/airports")] #[post("/airports")]
async fn create(airport: web::Json<Airport>) -> HttpResponse { async fn create(airport: web::Json<Airport>) -> HttpResponse {
match Airports::create(airport.into_inner()) { match Airports::create(airport.into_inner()) {
Ok(a) => HttpResponse::Ok().json(a), Ok(a) => HttpResponse::Created().json(a),
Err(err) => { Err(err) => {
error!("{}", err); error!("{}", err);
HttpResponse::InternalServerError().finish() err.to_http_response()
} }
} }
} }
@@ -79,7 +131,7 @@ async fn update(id: web::Path<i32>, airport: web::Json<Airport>) -> HttpResponse
Ok(a) => HttpResponse::Ok().json(a), Ok(a) => HttpResponse::Ok().json(a),
Err(err) => { Err(err) => {
error!("{}", err); error!("{}", err);
HttpResponse::InternalServerError().finish() err.to_http_response()
} }
} }
} }
@@ -87,19 +139,19 @@ async fn update(id: web::Path<i32>, airport: web::Json<Airport>) -> HttpResponse
#[delete("/airports/{id}")] #[delete("/airports/{id}")]
async fn delete(id: web::Path<i32>) -> HttpResponse { async fn delete(id: web::Path<i32>) -> HttpResponse {
match Airports::delete(id.into_inner()) { match Airports::delete(id.into_inner()) {
Ok(a) => HttpResponse::Ok().json(json!({ "deleted": a })), Ok(_) => HttpResponse::NoContent().finish(),
Err(err) => { Err(err) => {
error!("{}", err); error!("{}", err);
HttpResponse::InternalServerError().finish() err.to_http_response()
} }
} }
} }
pub fn init_routes(config: &mut web::ServiceConfig) { pub fn init_routes(config: &mut web::ServiceConfig) {
config.service(find_all); config.service(get_all);
config.service(find); config.service(get);
config.service(create); config.service(create);
config.service(update); config.service(update);
config.service(delete); config.service(delete);
config.service(setup); config.service(import);
} }

View File

@@ -1,5 +1,6 @@
use crate::{error_handler::CustomError, airports::{Airport, Airports}}; use crate::{error_handler::CustomError, airports::{Airport, Airports}};
use diesel::{r2d2::ConnectionManager, PgConnection}; use diesel::{r2d2::ConnectionManager, PgConnection};
use serde::{Deserialize, Serialize};
use crate::diesel_migrations::MigrationHarness; use crate::diesel_migrations::MigrationHarness;
use lazy_static::lazy_static; use lazy_static::lazy_static;
use log::{error, debug, info}; use log::{error, debug, info};
@@ -51,3 +52,17 @@ pub fn import_data() {
} }
debug!("Import complete"); debug!("Import complete");
} }
#[derive(Serialize, Deserialize)]
pub struct Metadata {
pub page: i32,
pub limit: i32,
pub pages: i32,
pub total: i32,
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub struct Coordinate {
pub lon: f64,
pub lat: f64
}

View File

@@ -1,6 +1,7 @@
use actix_web::http::StatusCode; use actix_web::http::StatusCode;
use actix_web::{HttpResponse, ResponseError}; use actix_web::{HttpResponse, ResponseError};
use diesel::result::Error as DieselError; use diesel::result::Error as DieselError;
use log::warn;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use serde_json::json; use serde_json::json;
use std::fmt; use std::fmt;
@@ -18,6 +19,17 @@ impl CustomError {
error_message, error_message,
} }
} }
pub fn to_http_response(&self) -> HttpResponse {
let status_code = match StatusCode::from_u16(self.error_status_code) {
Ok(s) => s,
Err(err) => {
warn!("{}", err);
StatusCode::INTERNAL_SERVER_ERROR
}
};
HttpResponse::build(status_code).body(self.error_message.to_string())
}
} }
impl fmt::Display for CustomError { impl fmt::Display for CustomError {

View File

@@ -1,162 +0,0 @@
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;
}
}

View File

@@ -1,16 +1,32 @@
use crate::error_handler::CustomError; use crate::{error_handler::CustomError, db::Metadata};
use crate::metars::Metars; use crate::metars::Metars;
use actix_web::{get, web, HttpResponse, Responder}; use actix_web::{get, web, HttpResponse, Responder};
use log::error;
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize)]
pub struct MetarsResponse {
pub data: Vec<Metars>,
pub meta: Metadata
}
#[get("metars/{ids}")] #[get("metars/{ids}")]
async fn get_all(ids: web::Path<String>) -> impl Responder { async fn get_all(ids: web::Path<String>) -> impl Responder {
let airports = web::block(|| Ok::<_, CustomError>(async {Metars::get_all(ids.into_inner()).await})) let airports = match web::block(|| Ok::<_, CustomError>(async {Metars::get_all(ids.into_inner()).await}))
.await .await
.unwrap() .unwrap()
.unwrap() .unwrap()
.await .await {
.unwrap(); Ok(a) => a,
HttpResponse::Ok().json(airports) Err(err) => {
error!("{}", err);
return err.to_http_response();
}
};
HttpResponse::Ok().json(MetarsResponse {
data: airports,
meta: Metadata { page: 0, limit: 0, pages: 0, total: 0 }
})
} }
pub fn init_routes(config: &mut web::ServiceConfig) { pub fn init_routes(config: &mut web::ServiceConfig) {

View File

@@ -10,6 +10,7 @@
}, },
"dependencies": { "dependencies": {
"@ant-design/cssinjs": "^1.17.0", "@ant-design/cssinjs": "^1.17.0",
"@blueprintjs/core": "^5.3.0",
"antd": "^5.9.0", "antd": "^5.9.0",
"axios": "^1.4.0", "axios": "^1.4.0",
"leaflet": "^1.9.4", "leaflet": "^1.9.4",

View File

@@ -1,9 +1,8 @@
import { getAirport } from '@/js/api/airport'; import { getAirport } from '@/app/_api/airport';
import { Airport } from '@/js/api/airport.types';
import Link from 'next/link'; import Link from 'next/link';
export default async function Page({ params }: { params: { icao: string } }) { export default async function Page({ params }: { params: { icao: string } }) {
const airport: Airport = await getAirport({ icao: params.icao }); const { data: airport } = await getAirport({ icao: params.icao });
return ( return (
<> <>
<div className='border-b border-gray-200 bg-gray-400 px-4 py-5 sm:px-6 flex justify-between'> <div className='border-b border-gray-200 bg-gray-400 px-4 py-5 sm:px-6 flex justify-between'>

View File

@@ -1,10 +1,10 @@
import React from 'react'; import React from 'react';
import RecoilRootWrapper from '@app/recoil-root-wrapper'; import RecoilRootWrapper from '@app/recoil-root-wrapper';
import Sidebar from '@/components/Sidebar'; import Sidebar from '@/app/_components/Sidebar';
import Topbar from '@/components/Topbar'; import Topbar from '@/app/_components/Topbar';
import 'styles/globals.css'; import 'styles/globals.css';
import 'styles/leaflet.css'; import 'styles/leaflet.css';
import StyledComponentsRegistry from '@/lib/AntdRegistry'; import StyledComponentsRegistry from '@/app/_lib/AntdRegistry';
import { Inter } from 'next/font/google'; import { Inter } from 'next/font/google';
const inter = Inter({ subsets: ['latin'] }); const inter = Inter({ subsets: ['latin'] });

View File

@@ -1,5 +1,5 @@
import React from 'react'; import React from 'react';
import Metar from '@/components/Metars'; import Metar from '@/app/_components/Metars';
export default function Page() { export default function Page() {
return <Metar />; return <Metar />;

View File

@@ -1,3 +1,3 @@
export default function Profile() { export default function Profile() {
return <></>;
} }

View File

@@ -0,0 +1,42 @@
import axios from 'axios';
import { Bounds, GetAirportResponse, GetAirportsResponse } from './airport.types';
interface GetAirportProps {
icao: string;
}
export async function getAirport({ icao }: GetAirportProps): Promise<GetAirportResponse> {
const response = await axios.get(`http://localhost:5000/airports/${icao}`).catch((error) => console.error(error));
return response?.data || { data: undefined };
}
interface GetAirportsProps {
bounds?: Bounds;
category?: string;
filter?: string;
page?: number;
limit?: number;
}
export async function getAirports({
bounds,
category,
filter,
limit = 10,
page = 1
}: GetAirportsProps): Promise<GetAirportsResponse> {
const response = await axios
.get(`http://localhost:5000/airports`, {
params: {
bounds: bounds
? `${bounds?.northEast.lat},${bounds?.northEast.lon},${bounds?.southWest.lat},${bounds?.southWest.lon}`
: undefined,
category: category ?? undefined,
filter: filter ?? undefined,
limit,
page
}
})
.catch((error) => console.error(error));
return response?.data || { data: [] };
}

View File

@@ -6,6 +6,16 @@ export enum AirportCategory {
LARGE = 'large_airport' LARGE = 'large_airport'
} }
export interface Bounds {
northEast: Coordinate;
southWest: Coordinate;
}
export interface Coordinate {
lat: number;
lon: number;
}
export interface Airport { export interface Airport {
icao: string; icao: string;
category: AirportCategory; category: AirportCategory;
@@ -25,3 +35,11 @@ export interface Airport {
}; };
metar?: Metar; metar?: Metar;
} }
export interface GetAirportResponse {
data: Airport;
}
export interface GetAirportsResponse {
data: Airport[];
}

View File

@@ -2,12 +2,16 @@ import axios from 'axios';
import { Airport } from './airport.types'; import { Airport } from './airport.types';
import { Metar } from './metar.types'; import { Metar } from './metar.types';
export async function getMetars(airports: Airport[]): Promise<Metar[]> { interface GetMetarsResponse {
data: Metar[];
}
export async function getMetars(airports: Airport[]): Promise<GetMetarsResponse> {
if (airports.length == 0) { if (airports.length == 0) {
return []; return { data: [] };
} }
const stationICAOs: string = airports.map((airport) => airport.icao).join(','); const stationICAOs: string = airports.map((airport) => airport.icao).join(',');
const url = `http://localhost:5000/metars/${stationICAOs}`; const url = `http://localhost:5000/metars/${stationICAOs}`;
const response = await axios.get(url).catch((error) => console.error(error)); const response = await axios.get(url).catch((error) => console.error(error));
return response?.data || []; return response?.data || { data: [] };
} }

View File

@@ -1,9 +1,9 @@
'use client'; 'use client';
import { getAirports } from '@/js/api/airport'; import { getAirports } from '@/app/_api/airport';
import { Airport } from '@/js/api/airport.types'; import { Airport } from '@/app/_api/airport.types';
import { getMetars } from '@/js/api/metar'; import { getMetars } from '@/app/_api/metar';
import { Metar } from '@/js/api/metar.types'; import { Metar } from '@/app/_api/metar.types';
import { FaLocationPin } from 'react-icons/fa6'; import { FaLocationPin } from 'react-icons/fa6';
import { DivIcon, LatLngBounds } from 'leaflet'; import { DivIcon, LatLngBounds } from 'leaflet';
import { useEffect, useState } from 'react'; import { useEffect, useState } from 'react';
@@ -41,7 +41,7 @@ export default function MapTiles() {
async function updateAirports(bounds: LatLngBounds) { async function updateAirports(bounds: LatLngBounds) {
const ne = bounds.getNorthEast(); const ne = bounds.getNorthEast();
const sw = bounds.getSouthWest(); const sw = bounds.getSouthWest();
const _airports = await getAirports({ const { data: _airports } = await getAirports({
bounds: { bounds: {
northEast: { lat: ne.lat, lon: ne.lng }, northEast: { lat: ne.lat, lon: ne.lng },
southWest: { lat: sw.lat, lon: sw.lng } southWest: { lat: sw.lat, lon: sw.lng }
@@ -49,7 +49,7 @@ export default function MapTiles() {
limit: 100, limit: 100,
page: 1 page: 1
}); });
const metars = await getMetars(_airports); const { data: metars } = await getMetars(_airports);
metars.forEach((metar) => { metars.forEach((metar) => {
_airports.forEach((airport) => { _airports.forEach((airport) => {
if (metar.station_id == airport.icao) { if (metar.station_id == airport.icao) {

View File

@@ -1,5 +1,5 @@
import { Airport } from '@/js/api/airport.types'; import { Airport } from '@/app/_api/airport.types';
import { Metar } from '@/js/api/metar.types'; import { Metar } from '@/app/_api/metar.types';
import { FaArrowsSpin, FaLocationArrow } from 'react-icons/fa6'; import { FaArrowsSpin, FaLocationArrow } from 'react-icons/fa6';
import { Modal } from 'antd'; import { Modal } from 'antd';
@@ -34,7 +34,7 @@ export default function MetarDialog({ airport, isOpen, onClose }: MetarDialogPro
} }
} }
return ( return (
<Modal title={`${airport.icao} ${airport.full_name}`} open={isOpen} onCancel={onClose} footer={[]}> <Modal title={`${airport.icao} ${airport.full_name}`} open={isOpen} onCancel={onClose} closable={false} footer={[]}>
<div className='min-w-0 flex-1 select-none'> <div className='min-w-0 flex-1 select-none'>
<hr /> <hr />
<p className='text-sm font-medium text-gray-500'>{airport.metar?.raw_text}</p> <p className='text-sm font-medium text-gray-500'>{airport.metar?.raw_text}</p>
@@ -45,24 +45,26 @@ export default function MetarDialog({ airport, isOpen, onClose }: MetarDialogPro
{airport.metar?.flight_category ? airport.metar?.flight_category : 'UNKN'} {airport.metar?.flight_category ? airport.metar?.flight_category : 'UNKN'}
</span> </span>
<div className='flex inline-block px-2'> <div className='flex inline-block px-2'>
<span className={`text-sm text-black ${windColor(airport.metar)} py-2 px-2 rounded-full`}> <span className={`text-sm text-black ${windColor(airport.metar)} py-2 px-3 rounded-full`}>
{airport.metar && airport.metar.wind_dir_degrees && Number(airport.metar.wind_dir_degrees) > 0 ? ( {airport.metar && airport.metar.wind_dir_degrees && Number(airport.metar.wind_dir_degrees) > 0 ? (
<FaLocationArrow <FaLocationArrow
className='pr-1' className='align-middle'
style={{ rotate: `${-45 + 180 + Number(airport.metar.wind_dir_degrees)}deg` }} style={{ rotate: `${-45 + 180 + Number(airport.metar.wind_dir_degrees)}deg` }}
/> />
) : ( ) : (
<></> <></>
)} )}
{airport.metar && airport.metar.wind_dir_degrees && airport.metar.wind_dir_degrees == 'VRB' ? ( {airport.metar && airport.metar.wind_dir_degrees && airport.metar.wind_dir_degrees == 'VRB' ? (
<FaArrowsSpin className='pr-1' /> <FaArrowsSpin className='align-middle' />
) : ( ) : (
<></> <></>
)} )}
<span className='align-middle pl-1.5'>
{airport.metar?.wind_speed_kt != undefined && airport.metar?.wind_speed_kt > 0 {airport.metar?.wind_speed_kt != undefined && airport.metar?.wind_speed_kt > 0
? `${airport.metar?.wind_speed_kt} KT` ? `${airport.metar?.wind_speed_kt} KT`
: 'CALM'} : 'CALM'}
</span> </span>
</span>
</div> </div>
</div> </div>
</div> </div>

View File

@@ -1,8 +1,8 @@
import { Metar } from '@/js/api/metar.types'; import { Metar } from '@/app/_api/metar.types';
import dynamic from 'next/dynamic'; import dynamic from 'next/dynamic';
export default async function Metar({ className = '' }: { className?: string }) { export default async function Metar({ className = '' }: { className?: string }) {
const Map = dynamic(() => import('@/components/Metars/MetarMap'), { const Map = dynamic(() => import('@/app/_components/Metars/MetarMap'), {
loading: () => ( loading: () => (
<div className='grid min-h-full place-items-center px-6 py-24 sm:py-32 lg:px-8'> <div className='grid min-h-full place-items-center px-6 py-24 sm:py-32 lg:px-8'>
<div className='text-center'> <div className='text-center'>

View File

@@ -0,0 +1,82 @@
'use client';
import { AutoComplete, Avatar, Modal } from 'antd';
import Link from 'next/link';
import { AiOutlineSearch, AiOutlineUser } from 'react-icons/ai';
import { Button } from '@blueprintjs/core';
import { useState } from 'react';
import { getAirports } from '@/app/_api/airport';
import { useRouter } from 'next/navigation';
const DEFAULT_ICON_SIZE = 40;
export default function Topbar() {
const [modalOpen, setModalOpen] = useState(false);
const [searchValue, setSearchValue] = useState('');
const [airports, setAirports] = useState<{ key: string; value: string; label: string }[]>([]);
const router = useRouter();
async function onSearch(value: string) {
setSearchValue(value);
const airportData = await getAirports({ filter: value });
setAirports(
airportData.data.map((airport) => ({
key: airport.icao,
value: airport.icao,
label: `${airport.icao} - ${airport.full_name}`
}))
);
}
function onSelect(value: string) {
setModalOpen(false);
setSearchValue('');
router.push(`/airport/${value}`);
}
function onClose() {
setModalOpen(false);
setSearchValue('');
}
return (
<>
<Modal
open={modalOpen}
closable={false}
onCancel={onClose}
footer={[]}
className='p-0'
title={'Search for Airports'}
>
<AutoComplete
className='w-full'
allowClear
autoFocus
value={searchValue}
options={airports}
onSelect={onSelect}
onSearch={onSearch}
placeholder='Search Airports...'
/>
</Modal>
<nav className='w-screen flex bg-gray-700 text-gray-200 justify-between'>
<div className='flex'>
<Link href={'/'} className='align-middle pt-2.5 pl-6 text-lg'>
<span>Aviation Weather</span>
</Link>
<Button
icon={<AiOutlineSearch size={24} className='float-left mr-2 hover:text-white' />}
className='my-1 ml-6 pl-10 pr-12 border-none rounded-lg bg-gray-800 text-base text-gray-200/75 hover:bg-gray-600 hover:text-white cursor-pointer'
onClick={() => setModalOpen(true)}
>
Search Airports...
</Button>
</div>
<Link className='my-1 mr-2' href={'/profile'}>
<Avatar shape='circle' size={DEFAULT_ICON_SIZE} icon={<AiOutlineUser />} />
</Link>
</nav>
</>
);
}

View File

@@ -1,7 +0,0 @@
export const airportsState = atom({
key: 'airportsState',
default: [] as Airport[]
});
import { Airport } from "@/js/airport";
import { atom } from "recoil";

View File

@@ -1,27 +0,0 @@
'use client';
import { Avatar } from 'antd';
import Search from 'antd/es/input/Search';
import { useRouter } from 'next/navigation';
import { AiOutlineUser } from 'react-icons/ai';
export default function Topbar() {
const router = useRouter();
function onSearch(value: string) {
router.push(`/airports/${value}`);
}
return (
<nav className='w-screen flex bg-gray-700 text-gray-200'>
<Search
placeholder='Search Airports...'
onSearch={onSearch}
enterButton
className='p-2'
style={{ width: '20em' }}
/>
<Avatar shape='square' size={48} icon={<AiOutlineUser />} />
</nav>
);
}

View File

@@ -1,45 +0,0 @@
import axios from 'axios';
import { Airport } from './airport.types';
interface GetAirportsProps {
bounds?: Bounds;
category?: string;
page?: number;
limit?: number;
}
export interface Bounds {
northEast: Coordinate;
southWest: Coordinate;
}
export interface Coordinate {
lat: number;
lon: number;
}
interface GetAirportProps {
icao: string;
}
export async function getAirport({ icao }: GetAirportProps) {
const response = await axios.get(`http://localhost:5000/airports/${icao}`).catch((error) => console.error(error));
return response?.data;
}
export async function getAirports({ bounds, category, limit = 10, page = 1 }: GetAirportsProps): Promise<Airport[]> {
const response = await axios
.get(`http://localhost:5000/airports`, {
params: {
ne_lat: bounds?.northEast.lat,
ne_lon: bounds?.northEast.lon,
sw_lat: bounds?.southWest.lat,
sw_lon: bounds?.southWest.lon,
category,
limit,
page
}
})
.catch((error) => console.error(error));
return response?.data || [];
}

View File

@@ -27,9 +27,10 @@
"baseUrl": ".", "baseUrl": ".",
"paths": { "paths": {
"@/*": ["./src/*"], "@/*": ["./src/*"],
"@api/*": ["src/app/_api"],
"@app/*": ["./src/app/*"], "@app/*": ["./src/app/*"],
"@components/*": ["src/components/*"], "@components/*": ["src/app/_components/*"],
"@js/*": ["src/js"] "@lib/*": ["src/app/_components/*"]
} }
}, },
"include": [ "include": [