use std::collections::BTreeMap;
use crate::document::{Linkage, Links, Relationship, ResourceIdentifier, ResourceObject};
pub trait RelationshipDef {
fn name(&self) -> &str;
fn target(&self) -> &str;
fn is_to_many(&self) -> bool;
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Rel {
name: &'static str,
target: &'static str,
to_many: bool,
}
impl Rel {
pub const fn to_one(name: &'static str, target: &'static str) -> Self {
Self {
name,
target,
to_many: false,
}
}
pub const fn to_many(name: &'static str, target: &'static str) -> Self {
Self {
name,
target,
to_many: true,
}
}
}
impl RelationshipDef for Rel {
fn name(&self) -> &str {
self.name
}
fn target(&self) -> &str {
self.target
}
fn is_to_many(&self) -> bool {
self.to_many
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NoRelationships {}
impl RelationshipDef for NoRelationships {
fn name(&self) -> &str {
match *self {}
}
fn target(&self) -> &str {
match *self {}
}
fn is_to_many(&self) -> bool {
match *self {}
}
}
pub trait Schema {
type Relationship: RelationshipDef;
fn name(&self) -> &str;
fn relationships(&self) -> &[Self::Relationship];
fn base_path(&self) -> &str;
}
#[derive(Debug, Clone, Copy)]
pub struct Serializer<'a, S: Schema> {
schema: &'a S,
}
impl<'a, S: Schema> Serializer<'a, S> {
pub fn new(schema: &'a S) -> Self {
Self { schema }
}
pub fn self_link(&self, id: &str) -> String {
format!("{}/{}", self.schema.base_path().trim_end_matches('/'), id)
}
pub fn record(&self, id: &str) -> Record<'a, S> {
self.record_owned(id.to_string())
}
pub fn record_owned(&self, id: String) -> Record<'a, S> {
Record {
schema: self.schema,
id,
attributes: BTreeMap::new(),
related: BTreeMap::new(),
}
}
pub fn serialize(
&self,
id: &str,
attributes: BTreeMap<String, serde_json::Value>,
related: &BTreeMap<String, Vec<String>>,
) -> ResourceObject {
let self_link = self.self_link(id);
let mut object = ResourceObject::new(self.schema.name(), id);
object.attributes = attributes;
for (name, ids) in related {
if let Some(rel) = self.relationship_at(&self_link, name, ids) {
object = object.relationship(name.clone(), rel);
}
}
object.with_links(Links::this(self_link))
}
pub fn relationship(&self, id: &str, name: &str, ids: &[String]) -> Option<Relationship> {
self.relationship_at(&self.self_link(id), name, ids)
}
fn relationship_at(&self, self_link: &str, name: &str, ids: &[String]) -> Option<Relationship> {
self.relationship_owned(self_link, name, ids.to_vec())
}
fn relationship_owned(
&self,
self_link: &str,
name: &str,
ids: Vec<String>,
) -> Option<Relationship> {
let def = self
.schema
.relationships()
.iter()
.find(|r| r.name() == name)?;
let identifiers: Vec<_> = ids
.into_iter()
.map(|target_id| ResourceIdentifier::new(def.target(), target_id))
.collect();
let data = if def.is_to_many() {
Linkage::Many(identifiers)
} else {
Linkage::One(identifiers.into_iter().next())
};
let mut this =
String::with_capacity(self_link.len() + "/relationships/".len() + name.len());
this.push_str(self_link);
this.push_str("/relationships/");
this.push_str(name);
let mut related = String::with_capacity(self_link.len() + 1 + name.len());
related.push_str(self_link);
related.push('/');
related.push_str(name);
Some(Relationship {
data: Some(data),
links: Some(Links::this(this).related(related)),
})
}
}
#[must_use = "a record does nothing until `build` is called"]
pub struct Record<'a, S: Schema> {
schema: &'a S,
id: String,
attributes: BTreeMap<String, serde_json::Value>,
related: BTreeMap<String, Vec<String>>,
}
impl<S: Schema> Record<'_, S> {
pub fn attr(mut self, name: impl Into<String>, value: impl Into<serde_json::Value>) -> Self {
self.attributes.insert(name.into(), value.into());
self
}
pub fn attrs(
mut self,
attributes: impl IntoIterator<Item = (String, serde_json::Value)>,
) -> Self {
self.attributes.extend(attributes);
self
}
pub fn rel(self, name: impl Into<String>, id: impl Into<String>) -> Self {
self.rel_many(name, [id.into()])
}
pub fn rel_many(
mut self,
name: impl Into<String>,
ids: impl IntoIterator<Item = String>,
) -> Self {
self.related.insert(name.into(), ids.into_iter().collect());
self
}
pub fn build(self) -> ResourceObject {
let serializer = Serializer::new(self.schema);
let self_link = serializer.self_link(&self.id);
let mut object = ResourceObject::new(self.schema.name(), self.id);
object.attributes = self.attributes;
for (name, ids) in self.related {
if let Some(rel) = serializer.relationship_owned(&self_link, &name, ids) {
object = object.relationship(name, rel);
}
}
object.with_links(Links::this(self_link))
}
}