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
//! Json Serializer (using [Serde](https://docs.serde.rs/serde_json/)).

use std::io;

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

use super::{Error, Result, Serializer};

/// JSON serializer (using [Serde](https://docs.serde.rs/serde_json/)).
///
/// # Examples
///
/// ```
/// use dodo::prelude::*;
/// # use serde::{Deserialize, Serialize};
/// # use uuid::Uuid;
/// #
/// # #[derive(Debug, Entity, Serialize, Deserialize, Eq, PartialEq)]
/// # #[serde(rename_all = "camelCase")]
/// # struct Person { id: Option<Uuid>, name: String, age: u64 }
/// #
/// # impl Person {
/// #    fn with_age(age : u64) -> Self { Self { id : None, name : "John Smith".into(), age }}
/// # }
///
/// type PersonRepository = Repository<Person, Directory, JsonSerializer>;
///
/// fn main() -> Result<(), Box<dyn std::error::Error>> {
/// #   let path  = tempfile::tempdir()?;
///     let directory = Directory::new(&path)?;
///     let mut repository = PersonRepository::new(directory);
///     Ok(())
/// }
/// ```
#[derive(Debug, Clone)]
pub struct JsonSerializer;

impl Serializer for JsonSerializer {
    fn serialize<T, W>(mut writer: W, value: &T) -> Result<()>
        where T: Serialize + DeserializeOwned,
              W: io::Write {
        serde_json::to_writer(&mut writer, value)?;
        writer.flush().map_err(From::from)
    }

    fn deserialize<T, R>(reader: R) -> Result<T>
        where T: Serialize + DeserializeOwned,
              R: io::Read {
        serde_json::from_reader(reader).map_err(From::from)
    }
}

impl From<serde_json::Error> for Error {
    fn from(error: serde_json::Error) -> Self {
        use serde_json::error::Category;
        match error.classify() {
            Category::Syntax | Category::Data => Self::Format(format!("{}", error)),
            _ => Self::Io(io::Error::new(io::ErrorKind::Other, format!("{}", error)))
        }
    }
}