grafbase_sdk/types/
resolver.rs

1use std::borrow::Cow;
2
3use serde::{Deserialize, de::DeserializeSeed};
4
5use crate::{
6    SdkError,
7    types::{ArgumentsId, DefinitionId, Directive, Field, SelectionSet, Variables},
8    wit,
9};
10
11/// Represents a resolved field in the context of a subgraph and its parent type
12#[derive(serde::Serialize, serde::Deserialize)]
13pub struct ResolvedField<'a> {
14    pub(crate) subgraph_name: &'a str,
15    pub(crate) directive_name: &'a str,
16    pub(crate) directive_arguments: &'a [u8],
17    pub(crate) fields: Cow<'a, [wit::Field]>,
18    pub(crate) root_field_ix: usize,
19}
20
21impl<'a> TryFrom<&'a [u8]> for ResolvedField<'a> {
22    type Error = SdkError;
23    fn try_from(value: &'a [u8]) -> Result<Self, Self::Error> {
24        postcard::from_bytes(value).map_err(|err| format!("Failed to deserialize field data: {err}").into())
25    }
26}
27
28impl From<ResolvedField<'_>> for Vec<u8> {
29    fn from(value: ResolvedField<'_>) -> Self {
30        postcard::to_stdvec(&value).expect("Failed to serialize ResolvedField")
31    }
32}
33
34impl<'a> ResolvedField<'a> {
35    /// Reference to the root field
36    pub fn as_ref(&self) -> Field<'_> {
37        Field {
38            fields: &self.fields,
39            field: &self.fields[self.root_field_ix],
40        }
41    }
42
43    /// Returns the name of the subgraph this field belongs to.
44    pub fn subgraph_name(&self) -> &'a str {
45        self.subgraph_name
46    }
47
48    /// Gets the alias of this field, if any
49    pub fn alias(&self) -> Option<&str> {
50        self.as_ref().alias()
51    }
52
53    /// Gets the arguments ID of this field, if any
54    pub fn arguments_id(&self) -> Option<ArgumentsId> {
55        self.as_ref().arguments_id()
56    }
57
58    /// Field definition id.
59    pub fn definition_id(&self) -> DefinitionId {
60        self.as_ref().definition_id()
61    }
62
63    /// Deserializes the arguments of this field into the specified type
64    pub fn arguments<'de, T>(&self, variables: &'de Variables) -> Result<T, SdkError>
65    where
66        T: Deserialize<'de>,
67    {
68        self.as_ref().arguments(variables)
69    }
70
71    /// Deserializes the arguments of this field into the specified type with the given seed.
72    pub fn arguments_seed<'de, Seed>(&self, variables: &'de Variables, seed: Seed) -> Result<Seed::Value, SdkError>
73    where
74        Seed: DeserializeSeed<'de>,
75    {
76        self.as_ref().arguments_seed(variables, seed)
77    }
78
79    /// Gets the selection set of this field
80    pub fn selection_set(&self) -> SelectionSet<'_> {
81        self.as_ref().selection_set()
82    }
83
84    /// Returns the resolver directive associated with this field
85    pub fn directive(&self) -> Directive<'a> {
86        Directive(super::DirectiveInner::NameAndArgs {
87            name: self.directive_name,
88            arguments: self.directive_arguments,
89        })
90    }
91}