inflectived/src/routes.rs

73 lines
1.8 KiB
Rust
Raw Normal View History

2021-12-25 17:30:14 -05:00
use std::fs;
use rocket::get;
use rocket::State;
use rocket::http::Status;
use rocket::response::{content, status};
use rocket::serde::json::Json;
use rusqlite::params;
use crate::database::WordDb;
#[get("/frontend")]
pub fn frontend() -> Option<content::Html<String>> {
match fs::read_to_string("static/index.html") {
Ok(file) => Some(content::Html(file)),
Err(_) => None
}
}
#[get("/langs/<lang>/words/<word>")]
2021-12-25 22:03:45 -05:00
pub fn get_entries(db: &State<WordDb>, lang: &str, word: &str) -> status::Custom<content::Json<String>> {
2021-12-31 12:22:05 -05:00
let conn = db.connect();
2021-12-25 17:30:14 -05:00
2021-12-31 12:22:05 -05:00
let mut statement = conn.prepare(&format!(
2021-12-25 22:03:45 -05:00
"SELECT content
FROM {}_words
WHERE word = ?",
lang)
).unwrap();
2021-12-25 17:30:14 -05:00
2021-12-25 22:03:45 -05:00
let mut rows = statement.query([word]).unwrap();
let mut words = String::new();
words.push('[');
while let Some(row) = rows.next().unwrap() {
let content: String = row.get(0).unwrap();
words.push_str(&content);
words.push(',');
2021-12-25 17:30:14 -05:00
}
2021-12-31 12:22:05 -05:00
// Remove last comma
2021-12-25 22:03:45 -05:00
if words.pop().unwrap() == '[' {
words.push('[');
}
words.push(']');
status::Custom(Status::Ok, content::Json(words))
2021-12-25 17:30:14 -05:00
}
#[get("/langs/<lang>/words?<like>&<limit>&<offset>")]
2021-12-25 22:03:45 -05:00
pub fn get_entries_like(db: &State<WordDb>, lang: &str, like: &str, limit: usize, offset: usize) -> Json<Vec<String>> {
2021-12-31 12:22:05 -05:00
let conn = db.connect();
2021-12-25 17:30:14 -05:00
2021-12-31 12:22:05 -05:00
let mut statement = conn.prepare(&format!(
2021-12-25 22:03:45 -05:00
"SELECT word
FROM {}_words
WHERE word LIKE ?
ORDER BY length(word) ASC
LIMIT ?
OFFSET ?",
lang)
2021-12-25 17:30:14 -05:00
).unwrap();
let mut rows = statement.query(params![format!("%{}%", like), limit, offset]).unwrap();
let mut words = Vec::new();
while let Some(row) = rows.next().unwrap() {
words.push(row.get(0).unwrap());
}
Json(words)
}