graphql_federated_graph/federated_graph/directives/
override.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
use crate::{StringId, SubgraphId};

/// Represents an `@override(graph: .., from: ...)` directive on a field in a subgraph.
#[derive(serde::Serialize, serde::Deserialize, Clone)]
pub struct Override {
    pub graph: SubgraphId,
    /// Points to a subgraph referenced by name, but this is _not_ validated to allow easier field
    /// migrations between subgraphs.
    pub from: OverrideSource,
    #[serde(default)]
    pub label: OverrideLabel,
}

#[derive(serde::Serialize, serde::Deserialize, Clone, Default, Debug, PartialEq, PartialOrd)]
pub enum OverrideLabel {
    Percent(u8),
    #[serde(other)]
    #[default]
    Unknown,
}

impl OverrideLabel {
    pub fn as_percent(&self) -> Option<u8> {
        if let Self::Percent(v) = self {
            Some(*v)
        } else {
            None
        }
    }
}

impl std::fmt::Display for OverrideLabel {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            OverrideLabel::Percent(percent) => {
                f.write_str("percent(")?;
                percent.fmt(f)?;
                f.write_str(")")
            }
            OverrideLabel::Unknown => Ok(()),
        }
    }
}

impl std::str::FromStr for OverrideLabel {
    type Err = &'static str;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        if let Some(percent) = s
            .strip_prefix("percent(")
            .and_then(|suffix| suffix.strip_suffix(')'))
            .and_then(|percent| u8::from_str(percent).ok())
        {
            Ok(OverrideLabel::Percent(percent))
        } else {
            Err(r#"Expected a field of the format "percent(<number>)" "#)
        }
    }
}

#[derive(Debug, serde::Serialize, serde::Deserialize, Clone, PartialEq, PartialOrd)]
pub enum OverrideSource {
    Subgraph(SubgraphId),
    Missing(StringId),
}