redsunlib/src/search.rs

48 lines
1.1 KiB
Rust
Raw Normal View History

2021-01-01 12:54:13 +13:00
// CRATES
2021-01-01 18:03:44 +13:00
use crate::utils::{error, fetch_posts, param, Post};
use actix_web::{HttpRequest, HttpResponse, Result};
2021-01-01 12:54:13 +13:00
use askama::Template;
// STRUCTS
#[derive(Template)]
#[allow(dead_code)]
#[template(path = "search.html", escape = "none")]
struct SearchTemplate {
posts: Vec<Post>,
query: String,
sub: String,
sort: (String, String),
ends: (String, String),
}
// SERVICES
2021-01-01 18:03:44 +13:00
pub async fn find(req: HttpRequest) -> Result<HttpResponse> {
2021-01-01 12:54:13 +13:00
let path = format!("{}.json?{}", req.path(), req.query_string());
2021-01-02 09:33:57 +13:00
let q = param(&path, "q");
let sort = if param(&path, "sort").is_empty() {
2021-01-01 12:54:13 +13:00
"relevance".to_string()
} else {
2021-01-02 09:33:57 +13:00
param(&path, "sort")
2021-01-01 12:54:13 +13:00
};
let sub = req.match_info().get("sub").unwrap_or("").to_string();
let posts = fetch_posts(path.clone(), String::new()).await;
if posts.is_err() {
2021-01-01 18:03:44 +13:00
error(posts.err().unwrap().to_string()).await
2021-01-01 12:54:13 +13:00
} else {
let items = posts.unwrap();
let s = SearchTemplate {
posts: items.0,
query: q,
2021-01-02 09:33:57 +13:00
sub,
sort: (sort, param(&path, "t")),
ends: (param(&path, "after"), items.1),
2021-01-01 12:54:13 +13:00
}
.render()
.unwrap();
Ok(HttpResponse::Ok().content_type("text/html").body(s))
}
}