Skip to content

Commit

Permalink
feat: add search api route
Browse files Browse the repository at this point in the history
  • Loading branch information
alexohneander committed Feb 12, 2024
1 parent 87c5f3b commit 655b2df
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 1 deletion.
20 changes: 19 additions & 1 deletion src/handlers/search.rs
Original file line number Diff line number Diff line change
@@ -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;
Expand All @@ -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!")
Expand All @@ -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)
}
1 change: 1 addition & 0 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down

0 comments on commit 655b2df

Please sign in to comment.