I WANNA DIE!

This commit is contained in:
BurnyLlama 2022-11-06 01:11:43 +01:00
parent c385836aa0
commit 40e8974d6b
5 changed files with 85 additions and 17 deletions

3
.gitignore vendored
View File

@ -19,3 +19,6 @@ Cargo.lock
# Added by cargo
/target
data/*.sqlite
.env

View File

@ -6,4 +6,6 @@ edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
rocket = "0.5.0-rc.2"
rocket = { version = "0.5.0-rc.2", features = ["json"] }
mysql = "22.2.0"
dotenv = "0.15.0"

44
src/database/mod.rs Normal file
View File

@ -0,0 +1,44 @@
use std::env;
use std::result::Result;
use std::error::Error;
use mysql::*;
use mysql::prelude::*;
use crate::types;
pub fn get_maps() -> Result<Vec<types::Map>, Box<dyn Error>> {
let mut conn = create_pool()?.get_conn()?;
let maps = conn.query_map(
"SELECT * FROM record_maps",
|(name, server, points, stars, mapper, timestamp)| types::Map {
name, server, points, stars, mapper, timestamp
}
)?;
Ok(maps)
}
pub fn get_map_by_name(name: &str) -> Result<Option<types::Map>, Box<dyn Error>> {
let mut conn = create_pool()?.get_conn()?;
let stmt = conn.prep("SELECT * FROM record_maps WHERE Map = ?")?;
let map = conn.exec_first(
&stmt,
(name,)
)?;
Ok(match map {
Some((name, server, points, stars, mapper, timestamp)) => Some(types::Map {
name, server, points, stars, mapper, timestamp
}),
None => None
})
}
pub fn create_pool() -> Result<Pool, Box<dyn Error>> {
let url = env::var("DB_URI")?;
let pool = Pool::new(url.as_str())?;
Ok(pool)
}

View File

@ -1,26 +1,41 @@
#[macro_use] extern crate rocket;
use rocket::serde::json::Json;
extern crate dotenv;
use dotenv::dotenv;
mod types;
mod database;
#[get("/")]
fn index() -> &'static str {
"Hello, world!"
#[get("/maps")]
fn get_all_maps() -> Option<Json<Vec<types::Map>>> {
match database::get_maps() {
Ok(maps) => Some(Json(maps)),
Err(err) => {
println!("{err}");
None
}
}
}
#[get("/map")]
fn map() -> String {
let map = types::Map {
name: "Test".into(),
server: "USA".into(),
points: 5,
stars: 3,
mapper: "Furo".into()
};
format!("Map {} by {}", map.name, map.mapper)
#[get("/maps/<map>")]
fn get_map_by_name(map: &str) -> Option<Json<types::Map>> {
match database::get_map_by_name(map) {
Ok(map) => match map {
Some(map) => Some(Json(map)),
None => None
},
Err(err) => {
println!("{err}");
None
}
}
}
#[launch]
fn rocket() -> _ {
rocket::build().mount("/", routes![index, map])
dotenv().ok();
rocket::build()
.mount("/", routes![get_all_maps, get_map_by_name])
}

View File

@ -1,8 +1,12 @@
#[derive(Debug)]
use rocket::serde::{Serialize, Deserialize};
#[derive(Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(crate = "rocket::serde")]
pub struct Map {
pub name: String,
pub server: String,
pub points: i8,
pub stars: i8,
pub mapper: String,
pub timestamp: String,
}