r2_data_persistence/operations/
map.rs

1use crate::entities::Map;
2use crate::models::map::{CreateMapModel, GetMapModel, UpdateMapModel};
3use crate::schema::maps::dsl::*;
4use diesel::associations::HasTable;
5use diesel::{PgConnection, QueryDsl, QueryResult, RunQueryDsl, SelectableHelper};
6use uuid::Uuid;
7
8pub fn create_map(
9    connection: &mut PgConnection,
10    model: CreateMapModel,
11) -> Result<GetMapModel, String> {
12    let result = diesel::insert_into(maps::table())
13        .values(to_entity(model))
14        .returning(Map::as_returning())
15        .get_result(connection);
16
17    match result {
18        Ok(entity) => Ok(to_model(entity)),
19        Err(error) => Err(format!("Error saving map: {}", error)),
20    }
21}
22
23pub fn get_map(connection: &mut PgConnection, key: &str) -> Option<GetMapModel> {
24    let result: QueryResult<Map> = maps.find(key).select(Map::as_select()).first(connection);
25
26    if let Ok(entity) = result {
27        return Some(to_model(entity));
28    }
29
30    None
31}
32
33pub fn get_all_maps(connection: &mut PgConnection) -> Result<Vec<GetMapModel>, String> {
34    let result = maps.select(Map::as_select()).load(connection);
35
36    match result {
37        Ok(entities) => Ok(entities.into_iter().map(to_model).collect()),
38        Err(error) => Err(format!("Error loading maps: {}", error)),
39    }
40}
41
42pub fn update_map(
43    connection: &mut PgConnection,
44    key: &str,
45    model: UpdateMapModel,
46) -> Result<GetMapModel, String> {
47    let map = diesel::update(maps.find(key))
48        .set::<UpdateMapModel>(model)
49        .returning(Map::as_returning())
50        .get_result(connection);
51
52    match map {
53        Ok(map) => Ok(to_model(map)),
54        Err(error) => Err(format!("Error updating map: {}", error)),
55    }
56}
57
58pub fn delete_map(connection: &mut PgConnection, key: &str) -> Result<(), String> {
59    let result = diesel::delete(maps.find(key)).execute(connection);
60
61    match result {
62        Ok(_) => Ok(()),
63        Err(error) => Err(format!("Error deleting map: {}", error)),
64    }
65}
66
67fn to_model(entity: Map) -> GetMapModel {
68    GetMapModel {
69        id: entity.id,
70        song: entity.song,
71    }
72}
73
74fn to_entity(model: CreateMapModel) -> Map {
75    Map {
76        id: Uuid::new_v4().to_string(),
77        song: model.song,
78    }
79}