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

62 lines
1.6 KiB
Rust

use std::sync::Arc;
use geoffrey_db::helper::load_location;
use geoffrey_db::query::QueryBuilder;
use geoffrey_models::models::locations::{Location, LocationDb};
use geoffrey_models::models::parameters::edit_params::EditParams;
use geoffrey_models::models::player::Player;
use geoffrey_models::models::response::api_error::GeoffreyAPIError;
use geoffrey_models::models::CommandLevel;
use crate::api_endpoint::{ApiEndpoint, RequestType};
use crate::commands::Command;
use crate::context::Context;
use crate::Result;
pub struct Edit {}
impl ApiEndpoint for Edit {
fn endpoint_name() -> String {
"edit".to_string()
}
fn request_type() -> RequestType {
RequestType::POST
}
}
impl Command for Edit {
type Req = EditParams;
type Resp = Location;
fn command_level() -> CommandLevel {
CommandLevel::REGISTERED
}
fn run_command(ctx: Arc<Context>, req: &Self::Req, user: Option<Player>) -> Result<Self::Resp> {
let user = user.unwrap();
let query = QueryBuilder::<LocationDb>::default()
.with_owner(user.id.unwrap())
.with_name(&req.loc_name);
let mut location = ctx
.db
.run_query(query)?
.pop()
.ok_or(GeoffreyAPIError::EntryNotFound)?;
if let Some(new_pos) = &req.new_pos {
location.position = *new_pos;
}
if let Some(new_name) = &req.new_name {
location.name = new_name.clone();
}
let location = ctx.db.insert(location)?;
load_location(&ctx.db, &location).map_err(|err| err.into())
}
}