use crate::context::Context;
use crate::error::JsonApiError;
pub fn read_attribute<T: crate::attribute::Attribute>(
document: &serde_json::Value,
name: &str,
ctx: &Context,
) -> Result<T, JsonApiError> {
let value = document
.pointer(&format!("/data/attributes/{name}"))
.unwrap_or(&serde_json::Value::Null);
T::read(value).ok_or_else(|| {
JsonApiError::invalid(
ctx,
format!("`{name}` is not of the expected type"),
format!("/data/attributes/{name}"),
)
})
}
pub fn read_relationship(document: &serde_json::Value, name: &str) -> Option<String> {
document
.pointer(&format!("/data/relationships/{name}/data/id"))
.and_then(|id| id.as_str())
.map(ToString::to_string)
}
pub fn read_relationships(document: &serde_json::Value, name: &str) -> Vec<String> {
document
.pointer(&format!("/data/relationships/{name}/data"))
.and_then(|data| data.as_array())
.map(|ids| {
ids.iter()
.filter_map(|id| id.get("id").and_then(|id| id.as_str()))
.map(ToString::to_string)
.collect()
})
.unwrap_or_default()
}
#[macro_export]
macro_rules! resource {
(
$resource:ident as $name:literal at $base:literal,
state: $state:ident,
schema: $schema:ident,
input: $input:ident,
id: $id:ident,
attributes: { $($field:ident : $ty:ty),* $(,)? }
$(, relationships: { $($rel:ident -> $arity:ident $target:literal),* $(,)? })?
$(,)?
) => {
#[doc = ::std::concat!("The JSON:API schema for [`", ::std::stringify!($resource), "`].")]
#[derive(Debug, Clone, Copy, Default)]
pub struct $schema;
impl $crate::serialize::Schema for $schema {
type Relationship = $crate::serialize::Rel;
fn name(&self) -> &str {
$name
}
fn base_path(&self) -> &str {
$base
}
fn relationships(&self) -> &[$crate::serialize::Rel] {
const RELATIONSHIPS: &[$crate::serialize::Rel] =
&[$($($crate::__rel_def!($rel, $arity, $target)),*)?];
RELATIONSHIPS
}
}
#[doc = ::std::concat!("A validated request body for [`", ::std::stringify!($resource), "`].")]
#[derive(Debug, Clone)]
pub struct $input {
$(
#[doc = ::std::concat!("The `", ::std::stringify!($field), "` attribute.")]
pub $field: $ty,
)*
$($(
#[doc = ::std::concat!("Linkage for the `", ::std::stringify!($rel), "` relationship.")]
pub $rel: $crate::__rel_input_ty!($arity),
)*)?
}
impl $crate::extract::FromRequest<$state> for $input {
async fn from_request(
request: ::axum::extract::Request,
state: &$state,
ctx: &$crate::context::Context,
) -> ::std::result::Result<Self, $crate::response::Errors> {
let validator = $crate::crud::validator(state, $name, ctx)?;
let document = $crate::extract::validated(request, ctx, validator).await?;
#[allow(unused_mut)]
let mut failures: ::std::vec::Vec<$crate::error::JsonApiError> =
::std::vec::Vec::new();
$(
let $field = match $crate::declare::read_attribute::<$ty>(
&document,
::std::stringify!($field),
ctx,
) {
::std::result::Result::Ok(value) => ::std::option::Option::Some(value),
::std::result::Result::Err(err) => {
failures.push(err);
::std::option::Option::None
}
};
)*
if !failures.is_empty() {
return ::std::result::Result::Err($crate::response::Errors(failures));
}
::std::result::Result::Ok(Self {
$(
$field: $field.expect("read succeeded"),
)*
$($(
$rel: $crate::__rel_read!(document, $rel, $arity),
)*)?
})
}
}
impl $resource {
pub fn attributes_schema() -> $crate::__serde_json::Value {
#[allow(unused_mut)]
let mut properties = $crate::__serde_json::Map::new();
#[allow(unused_mut)]
let mut required: ::std::vec::Vec<$crate::__serde_json::Value> = ::std::vec::Vec::new();
$(
properties.insert(
::std::string::String::from(::std::stringify!($field)),
<$ty as $crate::attribute::Attribute>::schema(),
);
if <$ty as $crate::attribute::Attribute>::required() {
required.push($crate::__serde_json::Value::from(::std::stringify!($field)));
}
)*
$crate::__serde_json::json!({
"type": "object",
"properties": $crate::__serde_json::Value::Object(properties),
"required": $crate::__serde_json::Value::Array(required),
})
}
pub fn validator() -> ::std::result::Result<
$crate::validation::DocumentValidator,
$crate::validation::BuildError,
> {
$crate::validation::DocumentValidator::builder(&$schema)
.attributes(Self::attributes_schema())
.build()
}
}
impl $crate::crud::Resource<$state> for $resource {
type Create = $input;
type Update = $input;
const NAME: &'static str = $name;
const PATH: &'static str = $base;
fn to_resource(
&self,
_state: &$state,
_ctx: &$crate::context::Context,
) -> ::std::result::Result<$crate::document::ResourceObject, $crate::error::JsonApiError>
{
#[allow(unused_mut)]
let mut record = $crate::serialize::Serializer::new(&$schema)
.record_owned(::std::string::ToString::to_string(&self.$id));
$(
record = record.attr(
::std::stringify!($field),
<$ty as $crate::attribute::Attribute>::write(&self.$field),
);
)*
$($(
record = $crate::__rel_write!(record, self, $rel, $arity);
)*)?
::std::result::Result::Ok(record.build())
}
}
};
}
#[doc(hidden)]
#[macro_export]
macro_rules! __rel_def {
($rel:ident, one, $target:literal) => {
$crate::serialize::Rel::to_one(::std::stringify!($rel), $target)
};
($rel:ident, many, $target:literal) => {
$crate::serialize::Rel::to_many(::std::stringify!($rel), $target)
};
($rel:ident, $other:ident, $target:literal) => {
::std::compile_error!(::std::concat!(
"unknown relationship arity `",
::std::stringify!($other),
"`; expected `one` or `many`"
))
};
}
#[doc(hidden)]
#[macro_export]
macro_rules! __rel_input_ty {
(one) => { ::std::option::Option<::std::string::String> };
(many) => { ::std::vec::Vec<::std::string::String> };
($other:ident) => {
::std::compile_error!(::std::concat!(
"unknown relationship arity `",
::std::stringify!($other),
"`; expected `one` or `many`"
))
};
}
#[doc(hidden)]
#[macro_export]
macro_rules! __rel_read {
($document:ident, $rel:ident, one) => {
$crate::declare::read_relationship(&$document, ::std::stringify!($rel))
};
($document:ident, $rel:ident, many) => {
$crate::declare::read_relationships(&$document, ::std::stringify!($rel))
};
}
#[doc(hidden)]
#[macro_export]
macro_rules! __rel_write {
($record:ident, $self:ident, $rel:ident, one) => {
$record.rel(
::std::stringify!($rel),
::std::string::ToString::to_string(&$self.$rel),
)
};
($record:ident, $self:ident, $rel:ident, many) => {
$record.rel_many(
::std::stringify!($rel),
$self.$rel.iter().map(::std::string::ToString::to_string),
)
};
}
#[macro_export]
macro_rules! registry {
($state:ident { $($field:ident : $resource:ty),* $(,)? } hooks: $hooks:ident $(,)?) => {
$crate::__registry_impl!($state { $($field : $resource),* } hooks: $hooks);
};
($state:ident { $($field:ident : $resource:ty),* $(,)? }) => {
$crate::__registry_impl!($state { $($field : $resource),* });
};
}
#[doc(hidden)]
#[macro_export]
macro_rules! __registry_impl {
($state:ident { $($field:ident : $resource:ty),* } $(hooks: $hooks:ident)?) => {
impl $crate::crud::Validators for $state {
$(
fn hooks(&self) -> ::std::option::Option<&$crate::hook::Hooks> {
::std::option::Option::Some(&self.$hooks)
}
)?
fn validator(
&self,
resource: &str,
) -> ::std::option::Option<&$crate::validation::DocumentValidator> {
match resource {
$(
<$resource as $crate::crud::Resource<$state>>::NAME => {
::std::option::Option::Some(&*self.$field)
}
)*
_ => ::std::option::Option::None,
}
}
}
};
}