restrepo 0.5.12

A collection of components for building restful webservices with actix-web
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
//! Provides traits for implementing uniform create, read, update and delete operations on resources

use async_trait::async_trait;
use serde::{Serialize, de::DeserializeOwned};

/// Implements reading a single, identified value from a datasource
/// ### Example
/// ```
/// use restrepo::service::ReadItem;
/// use std::collections::HashMap;
/// use async_trait::async_trait;
///
/// struct Data;
///
/// #[async_trait]
/// impl ReadItem<String> for Data {
///     type DataSource = HashMap<i32, String>;
///     type ItemIdentifier = i32;
///     type Error = std::io::Error;
///
///     async fn read_item(ds: &Self::DataSource, id: &Self::ItemIdentifier) -> Result<String, Self::Error> {
///         let val = ds.get(id).ok_or(std::io::Error::new(std::io::ErrorKind::NotFound,"not found"))?;
///         Ok(val.to_owned())
///     }
/// }
/// ```
#[async_trait]
pub trait ReadItem<T: DeserializeOwned + Serialize> {
    type DataSource;
    type ItemIdentifier;
    type Error;

    async fn read_item(ds: &Self::DataSource, id: &Self::ItemIdentifier) -> Result<T, Self::Error>;
}

/// Read a list of unidentified items from a datasource
/// ### Example
/// ```
/// use restrepo::service::ReadItemList;
/// use std::collections::HashMap;
/// use async_trait::async_trait;
///
/// struct Data;
///
/// #[async_trait]
/// impl ReadItemList<String> for Data {
///     type DataSource = HashMap<i32, String>;
///     type Error = std::io::Error;
///
///     async fn read_item_list(ds: &Self::DataSource) -> Result<Vec<String>, Self::Error> {
///         Ok(ds.values().cloned().collect())
///     }
/// }
/// ```
#[async_trait]
pub trait ReadItemList<T: DeserializeOwned + Serialize> {
    type DataSource;
    type Error;

    async fn read_item_list(ds: &Self::DataSource) -> Result<Vec<T>, Self::Error>;
}

/// Read a list of identified items from a datasource
/// ### Example
/// ```
/// use async_trait::async_trait;
/// use restrepo::service::ReadIdentifiedItemList;
///
/// struct Data;
///
/// #[async_trait]
/// impl ReadIdentifiedItemList<String> for Data {
///     type DataSource = Vec<(i32, String)>;
///     type ItemIdentifier = i32;
///     type Error = std::io::Error;
///
///     async fn read_identified_item_list(
///         ds: &Self::DataSource,
///         id: &Self::ItemIdentifier,
///     ) -> Result<Vec<String>, Self::Error> {
///         let val = ds
///             .iter()
///             .filter(|v| &v.0 == id)
///             .map(|v| v.1.clone())
///             .collect::<Vec<String>>();
///         Ok(val)
///     }
/// }
/// ```
#[async_trait]
pub trait ReadIdentifiedItemList<T: DeserializeOwned + Serialize> {
    type DataSource;
    type ItemIdentifier;
    type Error;

    async fn read_identified_item_list(
        ds: &Self::DataSource,
        id: &Self::ItemIdentifier,
    ) -> Result<Vec<T>, Self::Error>;
}

/// Implements writing a new a value to a datasource
/// ### Example
/// ```
/// use restrepo::service::CreateItem;
/// use std::{collections::HashMap, sync::Mutex};
/// use async_trait::async_trait;
///
/// struct Data;
///
/// #[async_trait]
/// impl CreateItem<String, usize> for Data {
///     type DataSource = Mutex<Vec<String>>;
///     type Error = std::io::Error;
///
///     async fn create_item(ds: &Self::DataSource, new_item: &String) -> Result<usize, Self::Error> {
///         let mut ds = ds.lock().unwrap();
///         let new_index = ds.len() + 1;
///         ds.push(new_item.to_owned());
///         Ok(new_index)
///     }
///
/// }
/// ```
#[async_trait]
pub trait CreateItem<T: DeserializeOwned + Serialize, R> {
    type DataSource;
    type Error;

    async fn create_item(ds: &Self::DataSource, new_item: &T) -> Result<R, Self::Error>;
}

/// Implements deleting a value from a datasource
/// ### Example
/// ```
/// use restrepo::service::DeleteItem;
/// use std::{collections::HashMap, sync::Mutex};
/// use async_trait::async_trait;
///
/// struct Data;
///
/// #[async_trait]
/// impl DeleteItem<()> for Data {
///     type DataSource = Mutex<Vec<Option<String>>>;
///     type ItemIdentifier = usize;
///     type ExtraParameters = Option<String>;
///     type Error = std::io::Error;
///
///     async fn delete_item(
///         ds: &Self::DataSource,
///         id: &Self::ItemIdentifier,
///         params: &Self::ExtraParameters,
///     ) -> Result<(), Self::Error> {
///         if let Some(text) = params {
///             println!("{text}")
///         };
///         let mut ds = ds.lock().unwrap();
///         ds[*id] = None;
///         Ok(())
///     }
/// }
/// ```
#[async_trait]
pub trait DeleteItem<R: DeserializeOwned + Serialize> {
    type DataSource;
    type ItemIdentifier;
    type ExtraParameters;
    type Error;

    async fn delete_item(
        ds: &Self::DataSource,
        id: &Self::ItemIdentifier,
        params: &Self::ExtraParameters,
    ) -> Result<R, Self::Error>;
}

/// Implements updating an existing value in a datasource
///
///  Example
/// ```
/// use restrepo::service::UpdateItem;
/// use std::{collections::HashMap, sync::Mutex};
/// use async_trait::async_trait;
///
/// struct Data;
///
/// #[async_trait]
/// impl UpdateItem<String, Option<String>> for Data {
///     type DataSource = Mutex<HashMap<usize, String>>;
///     type ItemIdentifier = usize;
///     type Error = std::io::Error;
///
///     async fn update_item(
///             ds: &Self::DataSource,
///             id: &Self::ItemIdentifier,
///             new_item: &String
///         ) -> Result<Option<String>, Self::Error> {
///         let mut ds = ds.lock().unwrap();
///         Ok(ds.insert(*id, new_item.clone()))
///     }
/// }
/// ```
#[async_trait]
pub trait UpdateItem<T: DeserializeOwned + Serialize, R> {
    type DataSource;
    type ItemIdentifier;
    type Error;

    async fn update_item(
        ds: &Self::DataSource,
        id: &Self::ItemIdentifier,
        item: &T,
    ) -> Result<R, Self::Error>;
}

#[cfg(test)]
mod tests {
    use super::*;
    use async_trait::async_trait;
    use std::collections::HashMap;
    use std::sync::Mutex;

    #[actix_web::test]
    async fn read_item_trait() {
        let mut ds: HashMap<i32, String> = HashMap::new();
        ds.insert(1, "Foo".to_string());

        struct Data;

        #[async_trait]
        impl ReadItem<String> for Data {
            type DataSource = HashMap<i32, String>;
            type ItemIdentifier = i32;
            type Error = std::io::Error;

            async fn read_item(
                ds: &Self::DataSource,
                id: &Self::ItemIdentifier,
            ) -> Result<String, Self::Error> {
                let val = ds.get(id).ok_or_else(|| {
                    std::io::Error::new(std::io::ErrorKind::NotFound, "not found")
                })?;
                Ok(val.to_owned())
            }
        }
        assert_eq!(Data::read_item(&ds, &1).await.unwrap(), "Foo");
    }

    #[actix_web::test]
    async fn read_item_list_trait() {
        let mut ds: HashMap<i32, String> = HashMap::new();
        ds.insert(1, "Foo".to_string());
        ds.insert(2, "Bar".to_string());

        struct Data;

        #[async_trait]
        impl ReadItemList<String> for Data {
            type DataSource = HashMap<i32, String>;
            type Error = std::io::Error;

            async fn read_item_list(ds: &Self::DataSource) -> Result<Vec<String>, Self::Error> {
                Ok(ds.values().cloned().collect())
            }
        }

        let item_list = Data::read_item_list(&ds).await.unwrap();

        assert!(item_list.contains(&"Foo".to_string()) && item_list.contains(&"Bar".to_string()));
    }

    #[actix_web::test]
    async fn read_identified_item_list_trait() {
        let ds = vec![
            (1, "Foo".to_string()),
            (2, "Bar".to_string()),
            (1, "Boo".to_string()),
        ];

        struct Data;

        #[async_trait]
        impl ReadIdentifiedItemList<String> for Data {
            type DataSource = Vec<(i32, String)>;
            type ItemIdentifier = (i32, String);
            type Error = std::io::Error;

            async fn read_identified_item_list(
                ds: &Self::DataSource,
                id: &Self::ItemIdentifier,
            ) -> Result<Vec<String>, Self::Error> {
                let val = ds
                    .iter()
                    .filter(|v| v.0 == id.0 && v.1.ends_with(&id.1))
                    .map(|v| v.1.clone())
                    .collect::<Vec<String>>();
                Ok(val)
            }
        }

        let item_list = Data::read_identified_item_list(&ds, &(1, "oo".to_string()))
            .await
            .unwrap();

        assert!(item_list.contains(&"Foo".to_string()) && item_list.contains(&"Boo".to_string()));
    }

    #[actix_web::test]
    async fn create_item_trait() {
        let data: Vec<String> = Vec::new();
        let ds = Mutex::new(data);

        struct Data;

        #[async_trait]
        impl CreateItem<String, usize> for Data {
            type DataSource = Mutex<Vec<String>>;
            type Error = std::io::Error;

            async fn create_item(
                ds: &Self::DataSource,
                new_item: &String,
            ) -> Result<usize, Self::Error> {
                let mut ds = ds.try_lock().unwrap();
                ds.push(new_item.clone());
                Ok(ds.len() - 1)
            }
        }
        assert_eq!(Data::create_item(&ds, &"Foo".to_string()).await.unwrap(), 0);
        assert_eq!(ds.lock().unwrap()[0], "Foo");
    }

    #[actix_web::test]
    async fn delete_item_trait() {
        let data: Vec<String> = vec![
            "This".to_owned(),
            "is".to_owned(),
            "a".to_owned(),
            "test".to_owned(),
        ];
        let ds = Mutex::new(data);

        struct Data;

        #[async_trait]
        impl DeleteItem<usize> for Data {
            type DataSource = Mutex<Vec<String>>;
            type ItemIdentifier = usize;
            type ExtraParameters = String;
            type Error = std::io::Error;

            async fn delete_item(
                ds: &Self::DataSource,
                id: &Self::ItemIdentifier,
                params: &Self::ExtraParameters,
            ) -> Result<usize, Self::Error> {
                let mut ds = ds.lock().unwrap();
                let o_val = ds[*id].clone();
                ds[*id] = Default::default();
                ds.push(format!("{params}: {o_val}"));
                Ok(*id)
            }
        }

        assert_eq!(
            Data::delete_item(&ds, &2usize, &"deleted".to_owned())
                .await
                .unwrap(),
            2
        );
        let ds_l = ds.lock().unwrap();
        assert_eq!(ds_l[0], "This");
        assert_eq!(ds_l[1], "is");
        assert_eq!(ds_l[2], String::default());
        assert_eq!(ds_l[3], "test");
        assert_eq!(ds_l[4], "deleted: a");
    }

    #[actix_web::test]
    async fn update_item_trait() {
        let mut data: HashMap<usize, String> = HashMap::new();
        data.insert(1, "Bar".to_string());
        let ds = Mutex::new(data);

        let id = 1;
        let item = "Foo".to_string();

        struct Data;

        #[async_trait]
        impl UpdateItem<String, Option<String>> for Data {
            type DataSource = Mutex<HashMap<usize, String>>;
            type ItemIdentifier = usize;
            type Error = std::io::Error;

            async fn update_item(
                ds: &Self::DataSource,
                id: &Self::ItemIdentifier,
                new_item: &String,
            ) -> Result<Option<String>, Self::Error> {
                let mut ds = ds.lock().unwrap();
                Ok(ds.insert(*id, new_item.clone()))
            }
        }

        let old_val = Data::update_item(&ds, &id, &item).await.unwrap();
        assert_eq!(old_val, Some("Bar".to_string()));
        assert_eq!(ds.lock().unwrap().get(&id), Some(&item));
    }
}