Builds a basic api with rocket.rs, updates index.html

This commit is contained in:
2019-02-02 15:27:13 +01:00
parent ee3271f772
commit 46532eee9e
9 changed files with 118 additions and 30 deletions

65
web/src/main.rs Normal file
View File

@@ -0,0 +1,65 @@
#![feature(proc_macro_hygiene, decl_macro)]
#[macro_use] extern crate rocket;
#[macro_use] extern crate rocket_contrib;
#[macro_use] extern crate serde_derive;
extern crate cookbook;
use std::path::Path;
use rocket::response::{NamedFile, status::NotFound};
#[get("/")]
fn index() -> Result<NamedFile, NotFound<String>> {
NamedFile::open(&Path::new("./html/index.html"))
.map_err(|_| NotFound(format!("Server error : index not found")))
}
mod api {
use cookbook::*;
use rocket_contrib::{
json::Json,
databases::diesel,
};
#[database("cookbook_db")]
pub struct CookbookDbConn(diesel::SqliteConnection);
#[derive(Serialize)]
pub struct Recipe {
id: i32,
title: String,
category: i16,
ingredients: String,
preparation: String,
}
impl Recipe {
fn from(rec: models::Recipe) -> Recipe {
Recipe {
id: rec.id,
title: rec.title,
category: rec.category as i16,
ingredients: rec.ingredients,
preparation: rec.preparation,
}
}
}
#[get("/list")]
pub fn recipes_list(conn: CookbookDbConn) -> Json<Vec<Recipe>> {
Json(
recipes::load_all(&conn)
.into_iter()
.map(|r| Recipe::from(r))
.collect()
)
}
}
fn main() {
rocket::ignite()
.attach(api::CookbookDbConn::fairing())
.mount("/", routes![index])
.mount("/api", routes![api::recipes_list]).launch();
}