Skip to content

Commit

Permalink
Add search RPC
Browse files Browse the repository at this point in the history
  • Loading branch information
bubelov committed Oct 8, 2024
1 parent 14a6161 commit 2f3efea
Show file tree
Hide file tree
Showing 4 changed files with 56 additions and 0 deletions.
16 changes: 16 additions & 0 deletions src/area/model.rs
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,22 @@ impl Area {
Ok(res)
}

pub fn select_by_search_query(search_query: &str, conn: &Connection) -> Result<Vec<Area>> {
let query = format!(
r#"
SELECT {ALL_COLUMNS}
FROM {TABLE}
WHERE LOWER(json_extract({COL_TAGS}, '$.name')) LIKE '%' || UPPER(:query) || '%'
ORDER BY {COL_UPDATED_AT}, {COL_ID}
"#
);
let res = conn
.prepare(&query)?
.query_map(named_params! { ":query": search_query }, mapper())?
.collect::<Result<Vec<_>, _>>()?;
Ok(res)
}

pub fn select_by_id_or_alias(id_or_alias: &str, conn: &Connection) -> Result<Option<Area>> {
match id_or_alias.parse::<i64>() {
Ok(id) => Area::select_by_id(id, conn),
Expand Down
1 change: 1 addition & 0 deletions src/rpc/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ pub mod remove_allowed_action;
pub mod remove_area;
pub mod remove_area_tag;
pub mod remove_element_tag;
pub mod search;
pub mod set_area_tag;
pub mod set_element_tag;
pub mod sync_elements;
38 changes: 38 additions & 0 deletions src/rpc/search.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
use crate::{admin, area::Area, Result};
use deadpool_sqlite::Pool;
use jsonrpc_v2::{Data, Params};
use serde::{Deserialize, Serialize};
use std::sync::Arc;

const NAME: &str = "search";

#[derive(Deserialize)]
pub struct Args {
pub password: String,
pub query: String,
}

#[derive(Serialize)]
pub struct Res {
pub name: String,
pub r#type: String,
pub id: i64,
}

pub async fn run(Params(args): Params<Args>, pool: Data<Arc<Pool>>) -> Result<Vec<Res>> {
admin::service::check_rpc(&args.password, NAME, &pool).await?;
let areas = pool
.get()
.await?
.interact(move |conn| Area::select_by_search_query(&args.query, conn))
.await??;
let res = areas
.into_iter()
.map(|it| Res {
name: it.name(),
r#type: "area".into(),
id: it.id,
})
.collect();
Ok(res)
}
1 change: 1 addition & 0 deletions src/server/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,7 @@ pub async fn run() -> Result<()> {
.with_method("addallowedaction", rpc::add_allowed_action::run)
.with_method("removeallowedaction", rpc::remove_allowed_action::run)
.with_method("getuseractivity", rpc::get_user_activity::run)
.with_method("search", rpc::search::run)
.finish()
.into_actix_web_service(),
),
Expand Down

0 comments on commit 2f3efea

Please sign in to comment.