rocket-pinboard/src/handlers/home.rs

53 lines
1.4 KiB
Rust

use std::collections::HashMap;
use rocket::serde::Serialize;
use rocket::{get, State};
use rocket_dyn_templates::Template;
use super::super::{Config, NoteStore};
#[derive(Serialize)]
#[serde(crate = "rocket::serde")]
struct IndexTemplateContext<'a> {
app_version: &'a str,
notes: Vec<HashMap<&'a str, &'a str>>,
title: String,
}
#[get("/")]
pub(crate) async fn index(notes: &State<NoteStore>, config: &State<Config>) -> Template {
let notes = notes.read().unwrap();
let mut note_kvs = vec![];
for note in notes.iter() {
let mut note_kv = HashMap::new();
note_kv.insert("id", note.id.as_ref());
note_kv.insert("name", note.name.as_ref());
note_kvs.push(note_kv);
}
let context = IndexTemplateContext {
app_version: env!("CARGO_PKG_VERSION"),
notes: note_kvs,
title: config.title.clone(),
};
Template::render("index", &context)
}
#[cfg(test)]
mod tests {
use rocket;
use rocket::http::{Accept, Status};
use rocket::local::blocking::Client;
#[test]
fn index() {
let client = Client::untracked(crate::build_rocket(Some("test"))).unwrap();
// Try to get the index and verify the body
let res = client.get("/").header(Accept::HTML).dispatch();
assert_eq!(res.status(), Status::Ok);
let body = res.into_string().unwrap();
assert!(body.contains("<span id=\"note-name\">Test</span>"));
}
}