Push
This commit is contained in:
79
src/rest/mod.rs
Normal file
79
src/rest/mod.rs
Normal file
@ -0,0 +1,79 @@
|
||||
mod restday;
|
||||
mod restreg;
|
||||
|
||||
use std::ops::Deref;
|
||||
|
||||
use chrono::{Duration, Local, NaiveDate};
|
||||
use rocket::{
|
||||
form::{self, Form, ValueField},
|
||||
fs::FileServer,
|
||||
http::{Cookie, CookieJar},
|
||||
response::Redirect,
|
||||
Build, Rocket, State,
|
||||
};
|
||||
use rocket_dyn_templates::{context, Template};
|
||||
use sea_orm::{Database, DatabaseConnection};
|
||||
|
||||
use super::models::{all::DayWithTrips, day, user};
|
||||
|
||||
#[derive(Debug)]
|
||||
struct NaiveDateForm(NaiveDate);
|
||||
|
||||
impl<'v> rocket::form::FromFormField<'v> for NaiveDateForm {
|
||||
fn from_value(field: ValueField<'v>) -> form::Result<'v, NaiveDateForm> {
|
||||
let naivedate = chrono::NaiveDate::parse_from_str(&field.value, "%Y-%m-%d").unwrap(); //TODO:
|
||||
//fixme
|
||||
Ok(NaiveDateForm(naivedate))
|
||||
}
|
||||
}
|
||||
|
||||
impl Deref for NaiveDateForm {
|
||||
type Target = NaiveDate;
|
||||
fn deref(&self) -> &Self::Target {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
#[get("/")]
|
||||
async fn index(db: &State<DatabaseConnection>, user: user::Model) -> Template {
|
||||
let mut data = Vec::new();
|
||||
for i in 0..6 {
|
||||
let date = (Local::now() + Duration::days(i)).date_naive();
|
||||
let day = day::Model::find_or_create_day(date, db.inner()).await;
|
||||
data.push(DayWithTrips::new(day, db.inner()).await);
|
||||
}
|
||||
|
||||
Template::render("index", context! { data, user })
|
||||
}
|
||||
|
||||
#[get("/name")]
|
||||
fn name() -> Template {
|
||||
Template::render("name", context! {})
|
||||
}
|
||||
|
||||
#[derive(FromForm)]
|
||||
struct NameForm {
|
||||
name: String,
|
||||
}
|
||||
|
||||
#[put("/name", data = "<name>")]
|
||||
fn savename(name: Form<NameForm>, cookies: &CookieJar) -> Redirect {
|
||||
cookies.add(Cookie::new("name", name.name.clone()));
|
||||
Redirect::to("/")
|
||||
}
|
||||
|
||||
#[catch(401)] //unauthorized
|
||||
fn unauthorized_error() -> Redirect {
|
||||
Redirect::to("/name")
|
||||
}
|
||||
|
||||
pub async fn start() -> Rocket<Build> {
|
||||
rocket::build()
|
||||
.attach(Template::fairing())
|
||||
.manage(Database::connect("sqlite://db.sqlite").await.unwrap())
|
||||
.mount("/public", FileServer::from("static/"))
|
||||
.mount("/", routes![index, name, savename])
|
||||
.mount("/day", restday::routes())
|
||||
.mount("/register", restreg::routes())
|
||||
.register("/", catchers![unauthorized_error])
|
||||
}
|
Reference in New Issue
Block a user