redlib/src/search.rs

56 lines
1.2 KiB
Rust
Raw Normal View History

2020-12-31 15:54:13 -08:00
// CRATES
2021-01-05 18:04:49 -08:00
use crate::utils::{cookie, error, fetch_posts, param, Post};
2021-01-02 20:50:23 -08:00
use actix_web::{HttpRequest, HttpResponse};
2020-12-31 15:54:13 -08:00
use askama::Template;
// STRUCTS
2021-01-02 22:37:54 -08:00
struct SearchParams {
q: String,
sort: String,
t: String,
before: String,
after: String,
restrict_sr: String,
}
2020-12-31 15:54:13 -08:00
#[derive(Template)]
#[template(path = "search.html", escape = "none")]
struct SearchTemplate {
posts: Vec<Post>,
sub: String,
2021-01-02 22:37:54 -08:00
params: SearchParams,
2021-01-05 18:04:49 -08:00
layout: String,
2020-12-31 15:54:13 -08:00
}
// SERVICES
2021-01-02 20:50:23 -08:00
pub async fn find(req: HttpRequest) -> HttpResponse {
2020-12-31 15:54:13 -08:00
let path = format!("{}.json?{}", req.path(), req.query_string());
2021-01-01 12:33:57 -08:00
let sort = if param(&path, "sort").is_empty() {
2020-12-31 15:54:13 -08:00
"relevance".to_string()
} else {
2021-01-01 12:33:57 -08:00
param(&path, "sort")
2020-12-31 15:54:13 -08:00
};
let sub = req.match_info().get("sub").unwrap_or("").to_string();
2021-01-01 15:28:13 -08:00
match fetch_posts(&path, String::new()).await {
2021-01-02 20:50:23 -08:00
Ok(posts) => HttpResponse::Ok().content_type("text/html").body(
SearchTemplate {
2021-01-01 15:28:13 -08:00
posts: posts.0,
sub,
2021-01-02 22:37:54 -08:00
params: SearchParams {
q: param(&path, "q"),
sort,
t: param(&path, "t"),
before: param(&path, "after"),
after: posts.1,
restrict_sr: param(&path, "restrict_sr"),
},
2021-01-05 18:04:49 -08:00
layout: cookie(req, "layout"),
2021-01-01 15:28:13 -08:00
}
.render()
2021-01-02 20:50:23 -08:00
.unwrap(),
),
2021-01-01 22:21:43 -08:00
Err(msg) => error(msg.to_string()).await,
2020-12-31 15:54:13 -08:00
}
}