Geoffrey-rs/geoffrey_api/src/commands/find.rs

58 lines
1.7 KiB
Rust

use crate::commands::{Command, RequestType};
use crate::context::Context;
use crate::Result;
use geoffrey_models::models::locations::{LocationDb, Location};
use geoffrey_models::models::player::Player;
use geoffrey_models::models::parameters::find_params::FindParams;
use geoffrey_models::models::parameters::CommandRequest;
use geoffrey_models::models::response::api_error::GeoffreyAPIError;
use geoffrey_models::models::CommandLevel;
use std::sync::Arc;
use geoffrey_db::helper::load_location;
pub struct FindCommand {}
impl Command for FindCommand {
type Req = CommandRequest<FindParams>;
type Resp = Vec<Location>;
fn command_name() -> String {
"find".to_string()
}
fn request_type() -> RequestType {
RequestType::GET
}
fn command_level() -> CommandLevel {
CommandLevel::ALL
}
fn run_command(ctx: Arc<Context>, req: Self::Req) -> Result<Self::Resp> {
let query = req.arguments.query.to_lowercase();
let players: Vec<u64> = ctx
.db
.filter(|_, player: &Player| {
let player_name = player.name.to_lowercase();
player_name.contains(&query)
})?
.map(|player| player.id.unwrap())
.collect();
let locations: Vec<LocationDb> = ctx
.db
.filter(|_, loc: &LocationDb| {
let name = loc.name.to_lowercase();
name.contains(&query) || loc.owners().iter().any(|owner_id| players.contains(owner_id))
}).map_err(|err| GeoffreyAPIError::from(err))?.collect();
let locations: Result<Vec<Location>> = locations.iter().map(|loc| load_location(&ctx.db, loc).map_err(|err| GeoffreyAPIError::from(err))).collect();
locations
}
}