feat: add search api route
This commit is contained in:
parent
87c5f3b000
commit
655b2df151
@ -1,4 +1,4 @@
|
||||
use actix_web::{web, HttpResponse, Responder};
|
||||
use actix_web::{web, HttpRequest, HttpResponse, Responder};
|
||||
use serde::Deserialize;
|
||||
|
||||
use crate::types::app_state::AppStateWithSearchEngine;
|
||||
@ -9,6 +9,12 @@ pub struct AddDocumentRequest {
|
||||
content: String,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct QueryRequest {
|
||||
query: String,
|
||||
}
|
||||
|
||||
|
||||
pub async fn add_document_to_index(data: web::Data<AppStateWithSearchEngine>, req: web::Json<AddDocumentRequest>) -> impl Responder {
|
||||
data.search_engine.lock().unwrap().index(&req.url, &req.content);
|
||||
HttpResponse::Created().body("Document added to index!")
|
||||
@ -17,4 +23,16 @@ pub async fn add_document_to_index(data: web::Data<AppStateWithSearchEngine>, re
|
||||
pub async fn get_number_of_documents(data: web::Data<AppStateWithSearchEngine>) -> impl Responder {
|
||||
let number_of_documents = data.search_engine.lock().unwrap().number_of_documents();
|
||||
HttpResponse::Ok().body(format!("Number of documents: {}", number_of_documents))
|
||||
}
|
||||
|
||||
pub async fn search(data: web::Data<AppStateWithSearchEngine>, req: web::Query<QueryRequest>) -> impl Responder {
|
||||
if req.query.is_empty() {
|
||||
return HttpResponse::BadRequest().body("Query is empty");
|
||||
}
|
||||
|
||||
// Get the query string from query parameters
|
||||
log::debug!("Searching for: {}", &req.query);
|
||||
|
||||
let results = data.search_engine.lock().unwrap().search(&req.query);
|
||||
HttpResponse::Ok().json(results)
|
||||
}
|
@ -38,6 +38,7 @@ async fn main() -> std::io::Result<()> {
|
||||
"/search/index/number_of_documents",
|
||||
web::get().to(search::get_number_of_documents),
|
||||
)
|
||||
.route("/search", web::get().to(search::search))
|
||||
})
|
||||
.bind(("127.0.0.1", 8080))?
|
||||
.run()
|
||||
|
Loading…
x
Reference in New Issue
Block a user