Skip to main content

laravel_data/
data.rs

1//! `Data`: the PHP package's base class.
2
3use 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
11/// A data object: the PHP package's `Data` class. Derive `Serialize` (and `Deserialize` to
12/// create it from input), then implement `Data`:
13///
14/// ```ignore
15/// #[derive(Serialize, Deserialize)]
16/// pub struct SongData {
17///     pub title: String,
18///     pub artist: String,
19/// }
20///
21/// impl Data for SongData {}
22///
23/// let song = SongData::from_value(json!({"title": "Never Gonna Give You Up", "artist": "Rick Astley"}))?;
24/// song.to_array();
25/// ```
26///
27/// Property names follow serde's attributes: `#[serde(rename = "..")]` and
28/// `#[serde(rename_all = "camelCase")]` are PHP's `MapName` attributes.
29pub trait Data: Serialize + Sized {
30    /// Lazy properties always included: `includeProperties()`.
31    fn include_properties(&self) -> Vec<&'static str> {
32        Vec::new()
33    }
34
35    /// Lazy properties always excluded: `excludeProperties()`.
36    fn exclude_properties(&self) -> Vec<&'static str> {
37        Vec::new()
38    }
39
40    /// The only properties output: `onlyProperties()`.
41    fn only_properties(&self) -> Vec<&'static str> {
42        Vec::new()
43    }
44
45    /// Properties never output: `exceptProperties()`.
46    fn except_properties(&self) -> Vec<&'static str> {
47        Vec::new()
48    }
49
50    /// Properties added to the output: `with()`.
51    fn with(&self) -> Map<String, Value> {
52        Map::new()
53    }
54
55    /// The key to wrap responses in: the class's `wrap`. `None` uses the configured key.
56    fn default_wrap(&self) -> Option<&'static str> {
57        None
58    }
59
60    /// The includes a request may ask for with `?include=`: `allowedRequestIncludes()`. Empty
61    /// allows none, `None` allows all.
62    fn allowed_request_includes() -> Option<Vec<&'static str>> {
63        Some(Vec::new())
64    }
65
66    /// The excludes a request may ask for with `?exclude=`: `allowedRequestExcludes()`.
67    fn allowed_request_excludes() -> Option<Vec<&'static str>> {
68        Some(Vec::new())
69    }
70
71    /// The only-properties a request may ask for with `?only=`: `allowedRequestOnly()`.
72    fn allowed_request_only() -> Option<Vec<&'static str>> {
73        Some(Vec::new())
74    }
75
76    /// The except-properties a request may ask for with `?except=`: `allowedRequestExcept()`.
77    fn allowed_request_except() -> Option<Vec<&'static str>> {
78        Some(Vec::new())
79    }
80
81    /// Creates the data object from a JSON value: `from()` with an array.
82    ///
83    /// # Errors
84    ///
85    /// Fails with a `422` naming the field when the value doesn't fit.
86    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    /// Creates the data object from anything serializable, such as a model: `from()`.
94    ///
95    /// # Errors
96    ///
97    /// As [`from_value`](Self::from_value).
98    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    /// Creates a list of data objects: `collect()`.
106    ///
107    /// # Errors
108    ///
109    /// As [`from_value`](Self::from_value).
110    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    /// The transformation of this object, with its own partials, additional data and wrap.
118    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    /// Includes lazy properties: `include()`.
135    fn include<S: AsRef<str>>(self, paths: impl IntoIterator<Item = S>) -> Transformation<Self> {
136        self.transformation().include(paths)
137    }
138
139    /// Excludes lazy properties: `exclude()`.
140    fn exclude<S: AsRef<str>>(self, paths: impl IntoIterator<Item = S>) -> Transformation<Self> {
141        self.transformation().exclude(paths)
142    }
143
144    /// Keeps only these properties: `only()`.
145    fn only<S: AsRef<str>>(self, paths: impl IntoIterator<Item = S>) -> Transformation<Self> {
146        self.transformation().only(paths)
147    }
148
149    /// Leaves these properties out: `except()`.
150    fn except<S: AsRef<str>>(self, paths: impl IntoIterator<Item = S>) -> Transformation<Self> {
151        self.transformation().except(paths)
152    }
153
154    /// Adds properties: `additional()`.
155    fn additional(self, additional: impl Serialize) -> Transformation<Self> {
156        self.transformation().additional(additional)
157    }
158
159    /// Wraps responses in a key: `wrap()`.
160    fn wrap(self, key: impl Into<String>) -> Transformation<Self> {
161        self.transformation().wrap(key)
162    }
163
164    /// The transformed object: `toArray()`.
165    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    /// The JSON text: `toJson()`.
181    fn to_json(&self) -> String {
182        Value::Object(self.to_array()).to_string()
183    }
184
185    /// The response for `request`, with the partials its query string asks for and the
186    /// statuses PHP gives: `201` for a `POST`, else `200`. `toResponse()`.
187    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
193/// Lists of data objects: PHP's `DataCollection` and `collect()`.
194pub trait DataCollection<T: Data> {
195    /// The list's transformation.
196    fn transformation(self) -> Transformation<Vec<T>>;
197
198    /// Includes lazy properties of each item: `include()`.
199    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    /// The response for `request`: `toResponse()`.
207    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
232/// Adds the partials of `?include=`, `?exclude=`, `?only=` and `?except=` that `D` allows.
233fn 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}