grafbase_sdk/types/
resolver.rs1use std::borrow::Cow;
2
3use serde::{Deserialize, de::DeserializeSeed};
4
5use crate::{
6 SdkError,
7 types::{ArgumentsId, DefinitionId, Directive, Field, FieldDefinition, SelectionSet, SubgraphSchema, Variables},
8 wit,
9};
10
11#[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 pub fn as_ref(&self) -> Field<'_> {
37 Field {
38 fields: &self.fields,
39 field: &self.fields[self.root_field_ix],
40 }
41 }
42
43 pub fn subgraph_name(&self) -> &'a str {
45 self.subgraph_name
46 }
47
48 pub fn arguments_id(&self) -> Option<ArgumentsId> {
50 self.as_ref().arguments_id()
51 }
52
53 pub fn definition<'s>(&self, schema: &'s SubgraphSchema) -> FieldDefinition<'s> {
55 schema
56 .field_definition(self.definition_id())
57 .expect("Field definition not found, the wrong subgraph may have been used.")
58 }
59
60 pub fn definition_id(&self) -> DefinitionId {
62 self.as_ref().definition_id()
63 }
64
65 pub fn arguments<'de, T>(&self, variables: &'de Variables) -> Result<T, SdkError>
67 where
68 T: Deserialize<'de>,
69 {
70 self.as_ref().arguments(variables)
71 }
72
73 pub fn arguments_seed<'de, Seed>(&self, variables: &'de Variables, seed: Seed) -> Result<Seed::Value, SdkError>
75 where
76 Seed: DeserializeSeed<'de>,
77 {
78 self.as_ref().arguments_seed(variables, seed)
79 }
80
81 pub fn selection_set(&self) -> SelectionSet<'_> {
83 self.as_ref().selection_set()
84 }
85
86 pub fn directive(&self) -> Directive<'a> {
88 Directive(super::DirectiveInner::NameAndArgs {
89 name: self.directive_name,
90 arguments: self.directive_arguments,
91 })
92 }
93}