use laravel::http::Request;
use serde::Serialize;
use serde::de::DeserializeOwned;
use serde_json::{Map, Value};
use crate::partials::Partials;
use crate::transform::{Context, Transformation};
pub trait Data: Serialize + Sized {
fn include_properties(&self) -> Vec<&'static str> {
Vec::new()
}
fn exclude_properties(&self) -> Vec<&'static str> {
Vec::new()
}
fn only_properties(&self) -> Vec<&'static str> {
Vec::new()
}
fn except_properties(&self) -> Vec<&'static str> {
Vec::new()
}
fn with(&self) -> Map<String, Value> {
Map::new()
}
fn default_wrap(&self) -> Option<&'static str> {
None
}
fn allowed_request_includes() -> Option<Vec<&'static str>> {
Some(Vec::new())
}
fn allowed_request_excludes() -> Option<Vec<&'static str>> {
Some(Vec::new())
}
fn allowed_request_only() -> Option<Vec<&'static str>> {
Some(Vec::new())
}
fn allowed_request_except() -> Option<Vec<&'static str>> {
Some(Vec::new())
}
fn from_value(value: Value) -> laravel::Result<Self>
where
Self: DeserializeOwned,
{
serde_json::from_value(value).map_err(|error| laravel::Error::new(422, error))
}
fn from_source(source: &impl Serialize) -> laravel::Result<Self>
where
Self: DeserializeOwned,
{
Self::from_value(serde_json::to_value(source).map_err(|error| laravel::Error::msg(error.to_string()))?)
}
fn collect<S: Serialize>(sources: impl IntoIterator<Item = S>) -> laravel::Result<Vec<Self>>
where
Self: DeserializeOwned,
{
sources.into_iter().map(|source| Self::from_source(&source)).collect()
}
fn transformation(self) -> Transformation<Self> {
let context = Context {
include: Partials::parse(self.include_properties()),
exclude: Partials::parse(self.exclude_properties()),
only: Partials::parse(self.only_properties()),
except: Partials::parse(self.except_properties()),
};
let additional = self.with();
let wrap = self.default_wrap().map(|key| Some(key.to_owned()));
let mut transformation = Transformation::new(self, context).additional(additional);
if let Some(wrap) = wrap {
transformation.wrap = Some(wrap);
}
transformation
}
fn include<S: AsRef<str>>(self, paths: impl IntoIterator<Item = S>) -> Transformation<Self> {
self.transformation().include(paths)
}
fn exclude<S: AsRef<str>>(self, paths: impl IntoIterator<Item = S>) -> Transformation<Self> {
self.transformation().exclude(paths)
}
fn only<S: AsRef<str>>(self, paths: impl IntoIterator<Item = S>) -> Transformation<Self> {
self.transformation().only(paths)
}
fn except<S: AsRef<str>>(self, paths: impl IntoIterator<Item = S>) -> Transformation<Self> {
self.transformation().except(paths)
}
fn additional(self, additional: impl Serialize) -> Transformation<Self> {
self.transformation().additional(additional)
}
fn wrap(self, key: impl Into<String>) -> Transformation<Self> {
self.transformation().wrap(key)
}
fn to_array(&self) -> Map<String, Value> {
let context = Context {
include: Partials::parse(self.include_properties()),
exclude: Partials::parse(self.exclude_properties()),
only: Partials::parse(self.only_properties()),
except: Partials::parse(self.except_properties()),
};
let mut value = crate::transform::transform(self, &context);
if let Value::Object(object) = &mut value {
object.extend(self.with());
return std::mem::take(object);
}
Map::new()
}
fn to_json(&self) -> String {
Value::Object(self.to_array()).to_string()
}
fn to_response(self, request: &Request) -> laravel::http::Response {
let transformation = with_request_partials::<Self, Self>(self.transformation(), request);
response(&transformation, request)
}
}
pub trait DataCollection<T: Data> {
fn transformation(self) -> Transformation<Vec<T>>;
fn include<S: AsRef<str>>(self, paths: impl IntoIterator<Item = S>) -> Transformation<Vec<T>>
where
Self: Sized,
{
self.transformation().include(paths)
}
fn to_response(self, request: &Request) -> laravel::http::Response
where
Self: Sized,
{
let transformation = with_request_partials::<T, Vec<T>>(self.transformation(), request);
response(&transformation, request)
}
}
impl<T: Data> DataCollection<T> for Vec<T> {
fn transformation(self) -> Transformation<Vec<T>> {
Transformation::new(self, Context::default())
}
}
fn response<V: Serialize>(transformation: &Transformation<V>, request: &Request) -> laravel::http::Response {
let status = if request.method() == laravel::http::Method::POST {
201
} else {
200
};
laravel::http::IntoResponse::into_response(laravel::http::Json(transformation.to_response_value()))
.with_status(status)
}
fn with_request_partials<D: Data, V: Serialize>(
mut transformation: Transformation<V>,
request: &Request,
) -> Transformation<V> {
let query: Vec<(String, String)> = request
.uri()
.query()
.map(|query| form_urlencoded::parse(query.as_bytes()).into_owned().collect())
.unwrap_or_default();
let requested = |name: &str, allowed: Option<Vec<&'static str>>| -> Vec<String> {
let values: Vec<String> = query
.iter()
.filter(|(key, _)| key == name)
.flat_map(|(_, value)| value.split(',').map(|part| part.trim().to_owned()).collect::<Vec<_>>())
.filter(|part| !part.is_empty())
.collect();
match allowed {
None => values,
Some(allowed) => values
.into_iter()
.filter(|value| allowed.iter().any(|allowed| *allowed == "*" || value == allowed))
.collect(),
}
};
transformation = transformation.include(requested("include", D::allowed_request_includes()));
transformation = transformation.exclude(requested("exclude", D::allowed_request_excludes()));
transformation = transformation.only(requested("only", D::allowed_request_only()));
transformation.except(requested("except", D::allowed_request_except()))
}