1use laravel::http::Request;
4use serde::Serialize;
5use serde::de::DeserializeOwned;
6use serde_json::{Map, Value};
7
8use crate::partials::Partials;
9use crate::transform::{Context, Transformation};
10
11pub trait Data: Serialize + Sized {
30 fn include_properties(&self) -> Vec<&'static str> {
32 Vec::new()
33 }
34
35 fn exclude_properties(&self) -> Vec<&'static str> {
37 Vec::new()
38 }
39
40 fn only_properties(&self) -> Vec<&'static str> {
42 Vec::new()
43 }
44
45 fn except_properties(&self) -> Vec<&'static str> {
47 Vec::new()
48 }
49
50 fn with(&self) -> Map<String, Value> {
52 Map::new()
53 }
54
55 fn default_wrap(&self) -> Option<&'static str> {
57 None
58 }
59
60 fn allowed_request_includes() -> Option<Vec<&'static str>> {
63 Some(Vec::new())
64 }
65
66 fn allowed_request_excludes() -> Option<Vec<&'static str>> {
68 Some(Vec::new())
69 }
70
71 fn allowed_request_only() -> Option<Vec<&'static str>> {
73 Some(Vec::new())
74 }
75
76 fn allowed_request_except() -> Option<Vec<&'static str>> {
78 Some(Vec::new())
79 }
80
81 fn from_value(value: Value) -> laravel::Result<Self>
87 where
88 Self: DeserializeOwned,
89 {
90 serde_json::from_value(value).map_err(|error| laravel::Error::new(422, error))
91 }
92
93 fn from_source(source: &impl Serialize) -> laravel::Result<Self>
99 where
100 Self: DeserializeOwned,
101 {
102 Self::from_value(serde_json::to_value(source).map_err(|error| laravel::Error::msg(error.to_string()))?)
103 }
104
105 fn collect<S: Serialize>(sources: impl IntoIterator<Item = S>) -> laravel::Result<Vec<Self>>
111 where
112 Self: DeserializeOwned,
113 {
114 sources.into_iter().map(|source| Self::from_source(&source)).collect()
115 }
116
117 fn transformation(self) -> Transformation<Self> {
119 let context = Context {
120 include: Partials::parse(self.include_properties()),
121 exclude: Partials::parse(self.exclude_properties()),
122 only: Partials::parse(self.only_properties()),
123 except: Partials::parse(self.except_properties()),
124 };
125 let additional = self.with();
126 let wrap = self.default_wrap().map(|key| Some(key.to_owned()));
127 let mut transformation = Transformation::new(self, context).additional(additional);
128 if let Some(wrap) = wrap {
129 transformation.wrap = Some(wrap);
130 }
131 transformation
132 }
133
134 fn include<S: AsRef<str>>(self, paths: impl IntoIterator<Item = S>) -> Transformation<Self> {
136 self.transformation().include(paths)
137 }
138
139 fn exclude<S: AsRef<str>>(self, paths: impl IntoIterator<Item = S>) -> Transformation<Self> {
141 self.transformation().exclude(paths)
142 }
143
144 fn only<S: AsRef<str>>(self, paths: impl IntoIterator<Item = S>) -> Transformation<Self> {
146 self.transformation().only(paths)
147 }
148
149 fn except<S: AsRef<str>>(self, paths: impl IntoIterator<Item = S>) -> Transformation<Self> {
151 self.transformation().except(paths)
152 }
153
154 fn additional(self, additional: impl Serialize) -> Transformation<Self> {
156 self.transformation().additional(additional)
157 }
158
159 fn wrap(self, key: impl Into<String>) -> Transformation<Self> {
161 self.transformation().wrap(key)
162 }
163
164 fn to_array(&self) -> Map<String, Value> {
166 let context = Context {
167 include: Partials::parse(self.include_properties()),
168 exclude: Partials::parse(self.exclude_properties()),
169 only: Partials::parse(self.only_properties()),
170 except: Partials::parse(self.except_properties()),
171 };
172 let mut value = crate::transform::transform(self, &context);
173 if let Value::Object(object) = &mut value {
174 object.extend(self.with());
175 return std::mem::take(object);
176 }
177 Map::new()
178 }
179
180 fn to_json(&self) -> String {
182 Value::Object(self.to_array()).to_string()
183 }
184
185 fn to_response(self, request: &Request) -> laravel::http::Response {
188 let transformation = with_request_partials::<Self, Self>(self.transformation(), request);
189 response(&transformation, request)
190 }
191}
192
193pub trait DataCollection<T: Data> {
195 fn transformation(self) -> Transformation<Vec<T>>;
197
198 fn include<S: AsRef<str>>(self, paths: impl IntoIterator<Item = S>) -> Transformation<Vec<T>>
200 where
201 Self: Sized,
202 {
203 self.transformation().include(paths)
204 }
205
206 fn to_response(self, request: &Request) -> laravel::http::Response
208 where
209 Self: Sized,
210 {
211 let transformation = with_request_partials::<T, Vec<T>>(self.transformation(), request);
212 response(&transformation, request)
213 }
214}
215
216impl<T: Data> DataCollection<T> for Vec<T> {
217 fn transformation(self) -> Transformation<Vec<T>> {
218 Transformation::new(self, Context::default())
219 }
220}
221
222fn response<V: Serialize>(transformation: &Transformation<V>, request: &Request) -> laravel::http::Response {
223 let status = if request.method() == laravel::http::Method::POST {
224 201
225 } else {
226 200
227 };
228 laravel::http::IntoResponse::into_response(laravel::http::Json(transformation.to_response_value()))
229 .with_status(status)
230}
231
232fn with_request_partials<D: Data, V: Serialize>(
234 mut transformation: Transformation<V>,
235 request: &Request,
236) -> Transformation<V> {
237 let query: Vec<(String, String)> = request
238 .uri()
239 .query()
240 .map(|query| form_urlencoded::parse(query.as_bytes()).into_owned().collect())
241 .unwrap_or_default();
242 let requested = |name: &str, allowed: Option<Vec<&'static str>>| -> Vec<String> {
243 let values: Vec<String> = query
244 .iter()
245 .filter(|(key, _)| key == name)
246 .flat_map(|(_, value)| value.split(',').map(|part| part.trim().to_owned()).collect::<Vec<_>>())
247 .filter(|part| !part.is_empty())
248 .collect();
249 match allowed {
250 None => values,
251 Some(allowed) => values
252 .into_iter()
253 .filter(|value| allowed.iter().any(|allowed| *allowed == "*" || value == allowed))
254 .collect(),
255 }
256 };
257 transformation = transformation.include(requested("include", D::allowed_request_includes()));
258 transformation = transformation.exclude(requested("exclude", D::allowed_request_excludes()));
259 transformation = transformation.only(requested("only", D::allowed_request_only()));
260 transformation.except(requested("except", D::allowed_request_except()))
261}