json_api/view/
render.rs

1use doc::{Data, Document, PrimaryData};
2use error::Error;
3use query::Query;
4
5/// A trait to render a given type as a document.
6///
7/// This trait is automatically implemented for any type which implements [`Resource`].
8///
9/// [`Resource`]: ../trait.Resource.html
10pub trait Render<T: PrimaryData> {
11    /// Attempts to render the given type as a document.
12    ///
13    /// Types that implement the [`Resource`] trait via the [`resource!`] macro can use
14    /// the optional query argument to match object field-sets and included resources
15    /// with what is present in the query.
16    ///
17    /// If a query does not have a matching field-set for a given type and the type in
18    /// question is a part of the document's primary data or included resources, each
19    /// attribute specified in the type's [`resource!`] macro invocation will be used.
20    ///
21    /// [`Resource`]: ../trait.Resource.html
22    /// [`resource!`]: ../macro.resource.html
23    fn render(self, query: Option<&Query>) -> Result<Document<T>, Error>;
24}
25
26impl<D, T> Render<D> for Option<T>
27where
28    D: PrimaryData,
29    T: Render<D> + Sized,
30{
31    fn render(self, query: Option<&Query>) -> Result<Document<D>, Error> {
32        match self {
33            Some(value) => value.render(query),
34            None => Ok(Document::Ok {
35                data: Data::Member(Box::new(None)),
36                included: Default::default(),
37                jsonapi: Default::default(),
38                links: Default::default(),
39                meta: Default::default(),
40            }),
41        }
42    }
43}