|
1 | 1 | use std::ops::Deref; |
2 | 2 |
|
3 | | -use crate::storage::base_storage::{BaseStorage, StorageConnector}; |
| 3 | +use crate::{ |
| 4 | + model::sidebar_dto::SidebarSyncDto, |
| 5 | + storage::base_storage::{BaseStorage, StorageConnector}, |
| 6 | +}; |
4 | 7 | use callisto::dynamic_sidebar; |
5 | 8 | use common::errors::MegaError; |
6 | 9 | use sea_orm::{ |
7 | 10 | ActiveModelTrait, |
8 | 11 | ActiveValue::{NotSet, Set}, |
9 | | - EntityTrait, QueryOrder, |
| 12 | + EntityTrait, QueryOrder, TransactionTrait, |
10 | 13 | }; |
11 | 14 |
|
12 | 15 | #[derive(Clone)] |
@@ -118,4 +121,57 @@ impl DynamicSidebarStorage { |
118 | 121 |
|
119 | 122 | Ok(model) |
120 | 123 | } |
| 124 | + |
| 125 | + pub async fn sync_sidebar( |
| 126 | + &self, |
| 127 | + items: Vec<SidebarSyncDto>, |
| 128 | + ) -> Result<Vec<dynamic_sidebar::Model>, MegaError> { |
| 129 | + if items.is_empty() { |
| 130 | + return Ok(Vec::new()); |
| 131 | + } |
| 132 | + |
| 133 | + // Begin a transaction |
| 134 | + let txn = self.get_connection().begin().await?; |
| 135 | + |
| 136 | + let mut res_models = Vec::with_capacity(items.len()); |
| 137 | + |
| 138 | + for item in items { |
| 139 | + if let Some(id) = item.id { |
| 140 | + // Update existing menu item |
| 141 | + if let Some(model) = dynamic_sidebar::Entity::find_by_id(id).one(&txn).await? { |
| 142 | + let mut active_model: dynamic_sidebar::ActiveModel = model.into(); |
| 143 | + |
| 144 | + active_model.public_id = Set(item.public_id); |
| 145 | + active_model.label = Set(item.label); |
| 146 | + active_model.href = Set(item.href); |
| 147 | + active_model.visible = Set(item.visible); |
| 148 | + active_model.order_index = Set(item.order_index); |
| 149 | + |
| 150 | + let updated = active_model.update(&txn).await?; |
| 151 | + res_models.push(updated); |
| 152 | + } else { |
| 153 | + return Err(MegaError::Other(format!( |
| 154 | + "Sidebar with id `{id}` not found" |
| 155 | + ))); |
| 156 | + } |
| 157 | + } else { |
| 158 | + // Insert new menu item |
| 159 | + let active_model = dynamic_sidebar::ActiveModel { |
| 160 | + id: NotSet, |
| 161 | + public_id: Set(item.public_id), |
| 162 | + label: Set(item.label), |
| 163 | + href: Set(item.href), |
| 164 | + visible: Set(item.visible), |
| 165 | + order_index: Set(item.order_index), |
| 166 | + }; |
| 167 | + let inserted = active_model.insert(&txn).await?; |
| 168 | + res_models.push(inserted); |
| 169 | + } |
| 170 | + } |
| 171 | + |
| 172 | + // Commit the transaction |
| 173 | + txn.commit().await?; |
| 174 | + |
| 175 | + Ok(res_models) |
| 176 | + } |
121 | 177 | } |
0 commit comments