navree_orm/attributes/resource.rs
1//! Records as API resources: the shapes front ends receive, with the
2//! `__type` subject navree-api's resources carry for permission checks,
3//! and field-level masks.
4//!
5//! A record is a resource of its own (its serialized JSON plus `"__type":
6//! "<Model>"`, [`Record::to_resource_json`]), or becomes a dedicated
7//! resource type ([`Resource`], [`Record::to_resource`]); a model names its
8//! resource with `#[model(resource = DealResource)]`
9//! ([`Record::resource`]). Masks keep the fields an ability permits
10//! ([`Record::to_value_masked`]).
11//!
12//! ```
13//! # use navree_orm::__doc_models::*;
14//! use navree_api::ApiResource;
15//! use navree_orm::attributes::Resource;
16//! use serde::Serialize;
17//!
18//! #[derive(Serialize)]
19//! struct TagResource {
20//! id: i64,
21//! label: String,
22//! }
23//!
24//! impl ApiResource for TagResource {
25//! const TYPE: &'static str = "Tag";
26//! }
27//!
28//! impl Resource<Tag> for TagResource {
29//! fn from_record(tag: &Record<Tag>) -> Self {
30//! TagResource { id: tag.id, label: format!("#{}", tag.name) }
31//! }
32//! }
33//!
34//! let tag = Record::new(Tag { id: 3, name: "vip".into(), color: "gold".into() });
35//! assert_eq!(
36//! tag.to_resource_json_as::<TagResource>(),
37//! serde_json::json!({"id": 3, "label": "#vip", "__type": "Tag"})
38//! );
39//! assert_eq!(tag.to_resource_json()?["__type"], "Tag");
40//! # Ok::<(), navree_orm::OrmError>(())
41//! ```
42
43use navree_api::{ApiResource, TYPE_FIELD, resource_json};
44
45use crate::attributes::serialize::output_key;
46use crate::collection::Collection;
47use crate::error::Result;
48use crate::model::Model;
49use crate::record::Record;
50
51/// A resource built from records of `M`: what an API returns for them
52/// (navree-api's [`ApiResource`]: serializable, with a subject type).
53pub trait Resource<M: Model>: ApiResource + Sized {
54 /// The resource of `record`.
55 fn from_record(record: &Record<M>) -> Self;
56}
57
58/// The resource a model declares (`#[model(resource = R)]`), so its records
59/// turn into it without naming it.
60pub trait HasResource: Model {
61 /// The model's resource.
62 type Resource: Resource<Self>;
63}
64
65impl<M: Model> Record<M> {
66 /// The record as resource `R`.
67 pub fn to_resource<R: Resource<M>>(&self) -> R {
68 R::from_record(self)
69 }
70
71 /// The record as the resource its model declares
72 /// (`#[model(resource = R)]`).
73 pub fn resource(&self) -> M::Resource
74 where
75 M: HasResource,
76 {
77 M::Resource::from_record(self)
78 }
79
80 /// The record as resource `R`, serialized with its `__type`.
81 pub fn to_resource_json_as<R: Resource<M>>(&self) -> serde_json::Value {
82 resource_json(&R::from_record(self))
83 }
84
85 /// The record as its own resource: its serialized JSON (visibility,
86 /// appends and relations applied) with `"__type"` set to the model's
87 /// name.
88 pub fn to_resource_json(&self) -> Result<serde_json::Value> {
89 let mut json = self.to_value()?;
90 if let serde_json::Value::Object(object) = &mut json {
91 object.insert(
92 TYPE_FIELD.to_owned(),
93 serde_json::Value::String(M::meta().name().to_owned()),
94 );
95 }
96 Ok(json)
97 }
98
99 /// The record's JSON keeping only the `allowed` names (columns,
100 /// fields, or output keys: what an ability's permitted fields list),
101 /// plus the key and `__type`; `None` keeps every name. Field-level
102 /// access control for serialized records:
103 /// `record.to_value_masked(Some(&ability.permitted_fields("read", "Deal", Some(&json), &columns)))`.
104 pub fn to_value_masked(&self, allowed: Option<&[String]>) -> Result<serde_json::Value> {
105 let json = self.to_resource_json()?;
106 Ok(mask::<M>(json, allowed))
107 }
108
109 /// The names a mask chooses from: the keys of the record's
110 /// serialized JSON.
111 pub fn field_names(&self) -> Result<Vec<String>> {
112 Ok(crate::attributes::serialize::record_object(self)?
113 .into_iter()
114 .map(|(key, _)| key)
115 .collect())
116 }
117}
118
119/// Keeps `allowed` (resolved to output keys), the key and `__type`.
120fn mask<M: Model>(json: serde_json::Value, allowed: Option<&[String]>) -> serde_json::Value {
121 let Some(allowed) = allowed else {
122 return json;
123 };
124 let meta = M::meta();
125 let mut keep: Vec<String> = allowed
126 .iter()
127 .filter_map(|name| output_key(meta, name))
128 .collect();
129 if let Some(key) = output_key(meta, meta.key_column()) {
130 keep.push(key);
131 }
132 keep.push(TYPE_FIELD.to_owned());
133 match json {
134 serde_json::Value::Object(mut object) => {
135 object.retain(|key, _| keep.contains(key));
136 serde_json::Value::Object(object)
137 }
138 other => other,
139 }
140}
141
142impl<M: Model> Collection<M> {
143 /// Every record as resource `R`.
144 pub fn to_resource_collection<R: Resource<M>>(&self) -> Vec<R> {
145 self.iter().map(R::from_record).collect()
146 }
147
148 /// Every record as the resource its model declares.
149 pub fn resources(&self) -> Vec<M::Resource>
150 where
151 M: HasResource,
152 {
153 self.iter().map(M::Resource::from_record).collect()
154 }
155
156 /// Every record as resource `R`, serialized with its `__type`, as a
157 /// JSON array.
158 pub fn to_resource_json_as<R: Resource<M>>(&self) -> serde_json::Value {
159 serde_json::Value::Array(self.iter().map(Record::to_resource_json_as::<R>).collect())
160 }
161
162 /// Every record's JSON keeping only the `allowed` names (see
163 /// [`Record::to_value_masked`]), as a JSON array.
164 pub fn to_value_masked(&self, allowed: Option<&[String]>) -> Result<serde_json::Value> {
165 self.iter()
166 .map(|record| record.to_value_masked(allowed))
167 .collect::<Result<Vec<_>>>()
168 .map(serde_json::Value::Array)
169 }
170}