grafbase_sdk/types/
subscription.rs

1use serde::Serialize;
2
3use crate::{cbor, wit, SdkError};
4
5use super::Error;
6
7/// List of items to be returned by a subscriptions.
8/// If there are no items to return, use the default value.
9pub struct SubscriptionOutput(wit::FieldOutput);
10
11impl From<SubscriptionOutput> for wit::FieldOutput {
12    fn from(output: SubscriptionOutput) -> Self {
13        output.0
14    }
15}
16
17impl SubscriptionOutput {
18    /// Create a new builder
19    pub fn builder() -> SubscriptionOutputBuilder {
20        SubscriptionOutputBuilder { items: Vec::new() }
21    }
22
23    /// Create a new builder with a given capacity
24    pub fn builder_with_capacity(capacity: usize) -> SubscriptionOutputBuilder {
25        SubscriptionOutputBuilder {
26            items: Vec::with_capacity(capacity),
27        }
28    }
29}
30
31/// Accumulator for setting the output individually for each `ResolverInput`.
32pub struct SubscriptionOutputBuilder {
33    items: Vec<Result<Vec<u8>, wit::Error>>,
34}
35
36impl SubscriptionOutputBuilder {
37    /// Push the output for a given `ResolverInput`.
38    pub fn push<T: Serialize>(&mut self, data: T) -> Result<(), SdkError> {
39        let data = cbor::to_vec(data)?;
40        self.items.push(Ok(data));
41        Ok(())
42    }
43
44    /// Push an error for a given `ResolverInput`.
45    pub fn push_error(&mut self, error: impl Into<Error>) {
46        self.items.push(Err(Into::<Error>::into(error).into()));
47    }
48
49    /// Build the `SubscriptionOutput`.
50    pub fn build(self) -> SubscriptionOutput {
51        SubscriptionOutput(wit::FieldOutput { outputs: self.items })
52    }
53}