coman/core/
collection_manager_ops.rs1use crate::core::errors::CollectionError;
2use crate::core::utils::merge_headers;
3use crate::{core::errors::CollectionResult, Collection, CollectionManager};
4
5impl CollectionManager {
6 pub fn get_collection(&self, name: &str) -> CollectionResult<Collection> {
8 let collections = self.load_collections()?;
9 collections
10 .into_iter()
11 .find(|c| c.name == name)
12 .ok_or_else(|| CollectionError::CollectionNotFound(name.to_string()))
13 }
14
15 pub fn add_collection(
19 &self,
20 name: &str,
21 url: &str,
22 headers: Vec<(String, String)>,
23 ) -> CollectionResult<()> {
24 let mut collections = self.load_collections()?;
25
26 if let Some(col) = collections.iter_mut().find(|c| c.name == name) {
27 col.url = url.to_string();
29 col.headers = headers;
30 } else {
31 collections.push(Collection {
33 name: name.to_string(),
34 url: url.to_string(),
35 headers,
36 requests: None,
37 });
38 }
39
40 self.save_collections(&collections)
41 }
42
43 pub fn delete_collection(&self, name: &str) -> CollectionResult<()> {
45 let mut collections = self.load_collections()?;
46 let original_len = collections.len();
47 collections.retain(|c| c.name != name);
48
49 if collections.len() == original_len {
50 return Err(CollectionError::CollectionNotFound(name.to_string()));
51 }
52
53 self.save_collections(&collections)
54 }
55
56 pub fn update_collection(
58 &self,
59 name: &str,
60 url: Option<&str>,
61 headers: Option<Vec<(String, String)>>,
62 ) -> CollectionResult<()> {
63 let mut collections = self.load_collections()?;
64
65 let col = collections
66 .iter_mut()
67 .find(|c| c.name == name)
68 .ok_or_else(|| CollectionError::CollectionNotFound(name.to_string()))?;
69
70 if let Some(url) = url {
71 col.url = url.to_string();
72 }
73
74 if let Some(new_headers) = headers {
75 col.headers = merge_headers(col.headers.clone(), &new_headers);
76 }
77
78 self.save_collections(&collections)
79 }
80
81 pub fn copy_collection(&self, name: &str, new_name: &str) -> CollectionResult<()> {
83 let mut collections = self.load_collections()?;
84
85 let col = collections
86 .iter()
87 .find(|c| c.name == name)
88 .ok_or_else(|| CollectionError::CollectionNotFound(name.to_string()))?;
89
90 let mut new_col = col.clone();
91 new_col.name = new_name.to_string();
92 collections.push(new_col);
93
94 self.save_collections(&collections)
95 }
96}