Skip to main content

jacquard_api/pub_leaflet/poll/
definition.rs

1// @generated by jacquard-lexicon. DO NOT EDIT.
2//
3// Lexicon: pub.leaflet.poll.definition
4//
5// This file was automatically generated from Lexicon schemas.
6// Any manual changes will be overwritten on the next regeneration.
7
8#[allow(unused_imports)]
9use alloc::collections::BTreeMap;
10
11#[allow(unused_imports)]
12use core::marker::PhantomData;
13use jacquard_common::CowStr;
14
15#[allow(unused_imports)]
16use jacquard_common::deps::codegen::unicode_segmentation::UnicodeSegmentation;
17use jacquard_common::types::collection::{Collection, RecordError};
18use jacquard_common::types::string::{AtUri, Cid, Datetime};
19use jacquard_common::types::uri::{RecordUri, UriError};
20use jacquard_common::xrpc::XrpcResp;
21use jacquard_derive::{IntoStatic, lexicon};
22use jacquard_lexicon::lexicon::LexiconDoc;
23use jacquard_lexicon::schema::LexiconSchema;
24
25#[allow(unused_imports)]
26use jacquard_lexicon::validation::{ConstraintError, ValidationPath};
27use serde::{Serialize, Deserialize};
28use crate::pub_leaflet::poll::definition;
29/// Record declaring a poll
30
31#[lexicon]
32#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
33#[serde(rename_all = "camelCase", rename = "pub.leaflet.poll.definition", tag = "$type")]
34pub struct Definition<'a> {
35    #[serde(skip_serializing_if = "Option::is_none")]
36    pub end_date: Option<Datetime>,
37    #[serde(borrow)]
38    pub name: CowStr<'a>,
39    #[serde(borrow)]
40    pub options: Vec<definition::DefinitionOption<'a>>,
41}
42
43/// Typed wrapper for GetRecord response with this collection's record type.
44
45#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic)]
46#[serde(rename_all = "camelCase")]
47pub struct DefinitionGetRecordOutput<'a> {
48    #[serde(skip_serializing_if = "Option::is_none")]
49    #[serde(borrow)]
50    pub cid: Option<Cid<'a>>,
51    #[serde(borrow)]
52    pub uri: AtUri<'a>,
53    #[serde(borrow)]
54    pub value: Definition<'a>,
55}
56
57
58#[lexicon]
59#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, IntoStatic, Default)]
60#[serde(rename_all = "camelCase")]
61pub struct DefinitionOption<'a> {
62    #[serde(skip_serializing_if = "Option::is_none")]
63    #[serde(borrow)]
64    pub text: Option<CowStr<'a>>,
65}
66
67impl<'a> Definition<'a> {
68    pub fn uri(
69        uri: impl Into<CowStr<'a>>,
70    ) -> Result<RecordUri<'a, DefinitionRecord>, UriError> {
71        RecordUri::try_from_uri(AtUri::new_cow(uri.into())?)
72    }
73}
74
75/// Marker type for deserializing records from this collection.
76
77#[derive(Debug, Serialize, Deserialize)]
78pub struct DefinitionRecord;
79impl XrpcResp for DefinitionRecord {
80    const NSID: &'static str = "pub.leaflet.poll.definition";
81    const ENCODING: &'static str = "application/json";
82    type Output<'de> = DefinitionGetRecordOutput<'de>;
83    type Err<'de> = RecordError<'de>;
84}
85
86impl From<DefinitionGetRecordOutput<'_>> for Definition<'_> {
87    fn from(output: DefinitionGetRecordOutput<'_>) -> Self {
88        use jacquard_common::IntoStatic;
89        output.value.into_static()
90    }
91}
92
93impl Collection for Definition<'_> {
94    const NSID: &'static str = "pub.leaflet.poll.definition";
95    type Record = DefinitionRecord;
96}
97
98impl Collection for DefinitionRecord {
99    const NSID: &'static str = "pub.leaflet.poll.definition";
100    type Record = DefinitionRecord;
101}
102
103impl<'a> LexiconSchema for Definition<'a> {
104    fn nsid() -> &'static str {
105        "pub.leaflet.poll.definition"
106    }
107    fn def_name() -> &'static str {
108        "main"
109    }
110    fn lexicon_doc() -> LexiconDoc<'static> {
111        lexicon_doc_pub_leaflet_poll_definition()
112    }
113    fn validate(&self) -> Result<(), ConstraintError> {
114        {
115            let value = &self.name;
116            #[allow(unused_comparisons)]
117            if <str>::len(value.as_ref()) > 500usize {
118                return Err(ConstraintError::MaxLength {
119                    path: ValidationPath::from_field("name"),
120                    max: 500usize,
121                    actual: <str>::len(value.as_ref()),
122                });
123            }
124        }
125        {
126            let value = &self.name;
127            {
128                let count = UnicodeSegmentation::graphemes(value.as_ref(), true).count();
129                if count > 100usize {
130                    return Err(ConstraintError::MaxGraphemes {
131                        path: ValidationPath::from_field("name"),
132                        max: 100usize,
133                        actual: count,
134                    });
135                }
136            }
137        }
138        Ok(())
139    }
140}
141
142impl<'a> LexiconSchema for DefinitionOption<'a> {
143    fn nsid() -> &'static str {
144        "pub.leaflet.poll.definition"
145    }
146    fn def_name() -> &'static str {
147        "option"
148    }
149    fn lexicon_doc() -> LexiconDoc<'static> {
150        lexicon_doc_pub_leaflet_poll_definition()
151    }
152    fn validate(&self) -> Result<(), ConstraintError> {
153        if let Some(ref value) = self.text {
154            #[allow(unused_comparisons)]
155            if <str>::len(value.as_ref()) > 500usize {
156                return Err(ConstraintError::MaxLength {
157                    path: ValidationPath::from_field("text"),
158                    max: 500usize,
159                    actual: <str>::len(value.as_ref()),
160                });
161            }
162        }
163        if let Some(ref value) = self.text {
164            {
165                let count = UnicodeSegmentation::graphemes(value.as_ref(), true).count();
166                if count > 50usize {
167                    return Err(ConstraintError::MaxGraphemes {
168                        path: ValidationPath::from_field("text"),
169                        max: 50usize,
170                        actual: count,
171                    });
172                }
173            }
174        }
175        Ok(())
176    }
177}
178
179pub mod definition_state {
180
181    pub use crate::builder_types::{Set, Unset, IsSet, IsUnset};
182    #[allow(unused)]
183    use ::core::marker::PhantomData;
184    mod sealed {
185        pub trait Sealed {}
186    }
187    /// State trait tracking which required fields have been set
188    pub trait State: sealed::Sealed {
189        type Options;
190        type Name;
191    }
192    /// Empty state - all required fields are unset
193    pub struct Empty(());
194    impl sealed::Sealed for Empty {}
195    impl State for Empty {
196        type Options = Unset;
197        type Name = Unset;
198    }
199    ///State transition - sets the `options` field to Set
200    pub struct SetOptions<S: State = Empty>(PhantomData<fn() -> S>);
201    impl<S: State> sealed::Sealed for SetOptions<S> {}
202    impl<S: State> State for SetOptions<S> {
203        type Options = Set<members::options>;
204        type Name = S::Name;
205    }
206    ///State transition - sets the `name` field to Set
207    pub struct SetName<S: State = Empty>(PhantomData<fn() -> S>);
208    impl<S: State> sealed::Sealed for SetName<S> {}
209    impl<S: State> State for SetName<S> {
210        type Options = S::Options;
211        type Name = Set<members::name>;
212    }
213    /// Marker types for field names
214    #[allow(non_camel_case_types)]
215    pub mod members {
216        ///Marker type for the `options` field
217        pub struct options(());
218        ///Marker type for the `name` field
219        pub struct name(());
220    }
221}
222
223/// Builder for constructing an instance of this type
224pub struct DefinitionBuilder<'a, S: definition_state::State> {
225    _state: PhantomData<fn() -> S>,
226    _fields: (
227        Option<Datetime>,
228        Option<CowStr<'a>>,
229        Option<Vec<definition::DefinitionOption<'a>>>,
230    ),
231    _lifetime: PhantomData<&'a ()>,
232}
233
234impl<'a> Definition<'a> {
235    /// Create a new builder for this type
236    pub fn new() -> DefinitionBuilder<'a, definition_state::Empty> {
237        DefinitionBuilder::new()
238    }
239}
240
241impl<'a> DefinitionBuilder<'a, definition_state::Empty> {
242    /// Create a new builder with all fields unset
243    pub fn new() -> Self {
244        DefinitionBuilder {
245            _state: PhantomData,
246            _fields: (None, None, None),
247            _lifetime: PhantomData,
248        }
249    }
250}
251
252impl<'a, S: definition_state::State> DefinitionBuilder<'a, S> {
253    /// Set the `endDate` field (optional)
254    pub fn end_date(mut self, value: impl Into<Option<Datetime>>) -> Self {
255        self._fields.0 = value.into();
256        self
257    }
258    /// Set the `endDate` field to an Option value (optional)
259    pub fn maybe_end_date(mut self, value: Option<Datetime>) -> Self {
260        self._fields.0 = value;
261        self
262    }
263}
264
265impl<'a, S> DefinitionBuilder<'a, S>
266where
267    S: definition_state::State,
268    S::Name: definition_state::IsUnset,
269{
270    /// Set the `name` field (required)
271    pub fn name(
272        mut self,
273        value: impl Into<CowStr<'a>>,
274    ) -> DefinitionBuilder<'a, definition_state::SetName<S>> {
275        self._fields.1 = Option::Some(value.into());
276        DefinitionBuilder {
277            _state: PhantomData,
278            _fields: self._fields,
279            _lifetime: PhantomData,
280        }
281    }
282}
283
284impl<'a, S> DefinitionBuilder<'a, S>
285where
286    S: definition_state::State,
287    S::Options: definition_state::IsUnset,
288{
289    /// Set the `options` field (required)
290    pub fn options(
291        mut self,
292        value: impl Into<Vec<definition::DefinitionOption<'a>>>,
293    ) -> DefinitionBuilder<'a, definition_state::SetOptions<S>> {
294        self._fields.2 = Option::Some(value.into());
295        DefinitionBuilder {
296            _state: PhantomData,
297            _fields: self._fields,
298            _lifetime: PhantomData,
299        }
300    }
301}
302
303impl<'a, S> DefinitionBuilder<'a, S>
304where
305    S: definition_state::State,
306    S::Options: definition_state::IsSet,
307    S::Name: definition_state::IsSet,
308{
309    /// Build the final struct
310    pub fn build(self) -> Definition<'a> {
311        Definition {
312            end_date: self._fields.0,
313            name: self._fields.1.unwrap(),
314            options: self._fields.2.unwrap(),
315            extra_data: Default::default(),
316        }
317    }
318    /// Build the final struct with custom extra_data
319    pub fn build_with_data(
320        self,
321        extra_data: BTreeMap<
322            jacquard_common::deps::smol_str::SmolStr,
323            jacquard_common::types::value::Data<'a>,
324        >,
325    ) -> Definition<'a> {
326        Definition {
327            end_date: self._fields.0,
328            name: self._fields.1.unwrap(),
329            options: self._fields.2.unwrap(),
330            extra_data: Some(extra_data),
331        }
332    }
333}
334
335fn lexicon_doc_pub_leaflet_poll_definition() -> LexiconDoc<'static> {
336    #[allow(unused_imports)]
337    use jacquard_common::{CowStr, deps::smol_str::SmolStr, types::blob::MimeType};
338    use jacquard_lexicon::lexicon::*;
339    use alloc::collections::BTreeMap;
340    LexiconDoc {
341        lexicon: Lexicon::Lexicon1,
342        id: CowStr::new_static("pub.leaflet.poll.definition"),
343        defs: {
344            let mut map = BTreeMap::new();
345            map.insert(
346                SmolStr::new_static("main"),
347                LexUserType::Record(LexRecord {
348                    description: Some(CowStr::new_static("Record declaring a poll")),
349                    key: Some(CowStr::new_static("tid")),
350                    record: LexRecordRecord::Object(LexObject {
351                        required: Some(
352                            vec![
353                                SmolStr::new_static("name"), SmolStr::new_static("options")
354                            ],
355                        ),
356                        properties: {
357                            #[allow(unused_mut)]
358                            let mut map = BTreeMap::new();
359                            map.insert(
360                                SmolStr::new_static("endDate"),
361                                LexObjectProperty::String(LexString {
362                                    format: Some(LexStringFormat::Datetime),
363                                    ..Default::default()
364                                }),
365                            );
366                            map.insert(
367                                SmolStr::new_static("name"),
368                                LexObjectProperty::String(LexString {
369                                    max_length: Some(500usize),
370                                    max_graphemes: Some(100usize),
371                                    ..Default::default()
372                                }),
373                            );
374                            map.insert(
375                                SmolStr::new_static("options"),
376                                LexObjectProperty::Array(LexArray {
377                                    items: LexArrayItem::Ref(LexRef {
378                                        r#ref: CowStr::new_static("#option"),
379                                        ..Default::default()
380                                    }),
381                                    ..Default::default()
382                                }),
383                            );
384                            map
385                        },
386                        ..Default::default()
387                    }),
388                    ..Default::default()
389                }),
390            );
391            map.insert(
392                SmolStr::new_static("option"),
393                LexUserType::Object(LexObject {
394                    properties: {
395                        #[allow(unused_mut)]
396                        let mut map = BTreeMap::new();
397                        map.insert(
398                            SmolStr::new_static("text"),
399                            LexObjectProperty::String(LexString {
400                                max_length: Some(500usize),
401                                max_graphemes: Some(50usize),
402                                ..Default::default()
403                            }),
404                        );
405                        map
406                    },
407                    ..Default::default()
408                }),
409            );
410            map
411        },
412        ..Default::default()
413    }
414}