1use std::io::{Read, Write};
2
3use serde::de::DeserializeOwned;
4use serde_json;
5
6use doc::{Data, Document, PrimaryData};
7use error::Error;
8use query::Query;
9use value::{self, Value};
10use view::Render;
11
12pub fn from_doc<T, U>(doc: Document<T>) -> Result<U, Error>
14where
15 T: PrimaryData,
16 U: DeserializeOwned,
17{
18 match doc {
19 Document::Ok { data, included, .. } => {
20 let value = value::convert::to_json(match data {
21 Data::Member(data) => match *data {
22 Some(item) => item.flatten(&included),
23 None => Value::Null,
24 },
25 Data::Collection(data) => data.into_iter()
26 .map(|item| item.flatten(&included))
27 .collect(),
28 });
29
30 Ok(serde_json::from_value(value)?)
31 }
32 Document::Err { .. } => {
33 let e = Error::from("Document contains one or more error(s)");
34 Err(e)
35 }
36 }
37}
38
39pub fn from_reader<R, T, U>(data: R) -> Result<U, Error>
42where
43 R: Read,
44 T: PrimaryData,
45 U: DeserializeOwned,
46{
47 from_doc::<T, _>(serde_json::from_reader(data)?)
48}
49
50pub fn from_slice<T, U>(data: &[u8]) -> Result<U, Error>
53where
54 T: PrimaryData,
55 U: DeserializeOwned,
56{
57 from_doc::<T, _>(serde_json::from_slice(data)?)
58}
59
60pub fn from_str<T, U>(data: &str) -> Result<U, Error>
63where
64 T: PrimaryData,
65 U: DeserializeOwned,
66{
67 from_doc::<T, _>(serde_json::from_str(data)?)
68}
69
70pub fn to_doc<T, U>(value: T, query: Option<&Query>) -> Result<Document<U>, Error>
72where
73 T: Render<U>,
74 U: PrimaryData,
75{
76 value.render(query)
77}
78
79pub fn to_string<T, U>(value: T, query: Option<&Query>) -> Result<String, Error>
82where
83 T: Render<U>,
84 U: PrimaryData,
85{
86 Ok(serde_json::to_string(&to_doc(value, query)?)?)
87}
88
89pub fn to_string_pretty<T, U>(value: T, query: Option<&Query>) -> Result<String, Error>
92where
93 T: Render<U>,
94 U: PrimaryData,
95{
96 Ok(serde_json::to_string_pretty(&to_doc(value, query)?)?)
97}
98
99pub fn to_vec<T, U>(value: T, query: Option<&Query>) -> Result<Vec<u8>, Error>
102where
103 T: Render<U>,
104 U: PrimaryData,
105{
106 Ok(serde_json::to_vec(&to_doc(value, query)?)?)
107}
108
109pub fn to_vec_pretty<T, U>(value: T, query: Option<&Query>) -> Result<Vec<u8>, Error>
112where
113 T: Render<U>,
114 U: PrimaryData,
115{
116 Ok(serde_json::to_vec_pretty(&to_doc(value, query)?)?)
117}
118
119pub fn to_writer<W, T, U>(writer: W, value: T, query: Option<&Query>) -> Result<(), Error>
122where
123 W: Write,
124 T: Render<U>,
125 U: PrimaryData,
126{
127 Ok(serde_json::to_writer(writer, &to_doc(value, query)?)?)
128}
129
130pub fn to_writer_pretty<W, T, U>(
133 writer: W,
134 value: T,
135 query: Option<&Query>,
136) -> Result<(), Error>
137where
138 W: Write,
139 T: Render<U>,
140 U: PrimaryData,
141{
142 Ok(serde_json::to_writer_pretty(
143 writer,
144 &to_doc(value, query)?,
145 )?)
146}