Skip to main content

zero_client/
format.rs

1//! The shape a query's view materializes as (`packages/zero-types/src/format.ts`).
2
3use crate::ast::Aggregate;
4use crate::decode::{self, JsonCodable, Reader, Result};
5use crate::json::{Object, Value};
6use crate::strings;
7
8#[derive(Clone, Debug, PartialEq, Default)]
9pub struct Format {
10    pub singular: bool,
11    /// By name, in UTF-16 code unit order.
12    pub relationships: Vec<(String, Format)>,
13    /// Set when the query or relationship is an aggregate: it materializes as
14    /// the aggregate's value rather than rows. Implies `singular`.
15    pub aggregate: Option<Aggregate>,
16}
17
18impl Format {
19    /// Sets the format of the relationship `name`, keeping the
20    /// relationships in order.
21    pub fn set_relationship(&mut self, name: &str, format: Format) {
22        match self
23            .relationships
24            .binary_search_by(|(k, _)| strings::utf16(k, name))
25        {
26            Ok(i) => self.relationships[i].1 = format,
27            Err(i) => self.relationships.insert(i, (name.to_owned(), format)),
28        }
29    }
30}
31
32impl JsonCodable for Format {
33    fn from_json(v: &Value) -> Result<Self> {
34        let r = Reader::new(v, "object")?;
35        let mut relationships = r
36            .optional("relationships", |v| decode::record(v, Format::from_json))?
37            .unwrap_or_default();
38        relationships.sort_by(|a, b| strings::utf16(&a.0, &b.0));
39        Ok(Format {
40            singular: r.optional_bool("singular")?.unwrap_or(false),
41            relationships,
42            aggregate: r.optional("aggregate", Aggregate::from_json)?,
43        })
44    }
45
46    fn to_json(&self) -> Value {
47        let rels: Object = self
48            .relationships
49            .iter()
50            .map(|(k, f)| (k.clone(), f.to_json()))
51            .collect();
52        let mut o = Object::new();
53        o.insert("singular", Value::Bool(self.singular));
54        o.insert("relationships", Value::Object(rels));
55        if let Some(a) = &self.aggregate {
56            o.insert("aggregate", a.to_json());
57        }
58        Value::Object(o)
59    }
60}