Skip to main content

use_graphql/
lib.rs

1#![forbid(unsafe_code)]
2#![doc = include_str!("../README.md")]
3
4use core::{fmt, str::FromStr};
5use std::error::Error;
6
7/// Error returned when API primitive text or labels are invalid.
8#[derive(Clone, Copy, Debug, Eq, PartialEq)]
9pub enum ApiPrimitiveError {
10    /// The supplied value was empty after trimming.
11    Empty,
12    /// The supplied value used syntax this crate rejects.
13    Invalid,
14    /// The supplied label was not recognized.
15    Unknown,
16}
17
18impl fmt::Display for ApiPrimitiveError {
19    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
20        match self {
21            Self::Empty => formatter.write_str("API primitive value cannot be empty"),
22            Self::Invalid => formatter.write_str("invalid API primitive value"),
23            Self::Unknown => formatter.write_str("unknown API primitive label"),
24        }
25    }
26}
27
28impl Error for ApiPrimitiveError {}
29
30fn validate_api_text(value: &str) -> Result<&str, ApiPrimitiveError> {
31    let trimmed = value.trim();
32    if trimmed.is_empty() {
33        return Err(ApiPrimitiveError::Empty);
34    }
35    if trimmed.chars().any(char::is_control) {
36        return Err(ApiPrimitiveError::Invalid);
37    }
38    Ok(trimmed)
39}
40
41macro_rules! text_newtype {
42    ($name:ident) => {
43        #[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
44        pub struct $name(String);
45
46        impl $name {
47            /// Creates validated text metadata.
48            ///
49            /// # Errors
50            ///
51            /// Returns [ApiPrimitiveError] when the value is empty or contains control characters.
52            pub fn new(value: impl AsRef<str>) -> Result<Self, ApiPrimitiveError> {
53                validate_api_text(value.as_ref()).map(|value| Self(value.to_owned()))
54            }
55
56            /// Parses validated text metadata.
57            ///
58            /// # Errors
59            ///
60            /// Returns [ApiPrimitiveError] when validation fails.
61            pub fn parse(value: impl AsRef<str>) -> Result<Self, ApiPrimitiveError> {
62                Self::new(value)
63            }
64
65            /// Returns the stored text.
66            #[must_use]
67            pub fn as_str(&self) -> &str {
68                &self.0
69            }
70
71            /// Consumes the value and returns the stored text.
72            #[must_use]
73            pub fn into_string(self) -> String {
74                self.0
75            }
76        }
77
78        impl AsRef<str> for $name {
79            fn as_ref(&self) -> &str {
80                self.as_str()
81            }
82        }
83
84        impl fmt::Display for $name {
85            fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
86                formatter.write_str(self.as_str())
87            }
88        }
89
90        impl FromStr for $name {
91            type Err = ApiPrimitiveError;
92
93            fn from_str(value: &str) -> Result<Self, Self::Err> {
94                Self::new(value)
95            }
96        }
97
98        impl TryFrom<&str> for $name {
99            type Error = ApiPrimitiveError;
100
101            fn try_from(value: &str) -> Result<Self, Self::Error> {
102                Self::new(value)
103            }
104        }
105    };
106}
107
108text_newtype!(GraphqlName);
109text_newtype!(TypeName);
110text_newtype!(FieldName);
111text_newtype!(OperationName);
112text_newtype!(DirectiveName);
113text_newtype!(ArgumentName);
114text_newtype!(VariableName);
115
116/// `GraphQL` operation kind labels.
117#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
118pub enum GraphqlOperationKind {
119    /// A stable label variant.
120    Query,
121    /// A stable label variant.
122    Mutation,
123    /// A stable label variant.
124    Subscription,
125}
126
127impl GraphqlOperationKind {
128    /// Returns the stable label.
129    #[must_use]
130    pub const fn as_str(self) -> &'static str {
131        match self {
132            Self::Query => "query",
133            Self::Mutation => "mutation",
134            Self::Subscription => "subscription",
135        }
136    }
137}
138
139impl Default for GraphqlOperationKind {
140    fn default() -> Self {
141        Self::Query
142    }
143}
144
145impl fmt::Display for GraphqlOperationKind {
146    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
147        formatter.write_str(self.as_str())
148    }
149}
150
151impl FromStr for GraphqlOperationKind {
152    type Err = ApiPrimitiveError;
153
154    fn from_str(value: &str) -> Result<Self, Self::Err> {
155        let trimmed = value.trim();
156        if trimmed.is_empty() {
157            return Err(ApiPrimitiveError::Empty);
158        }
159        let normalized = trimmed.to_ascii_lowercase().replace('_', "-");
160        match normalized.as_str() {
161            "query" => Ok(Self::Query),
162            "mutation" => Ok(Self::Mutation),
163            "subscription" => Ok(Self::Subscription),
164            _ => Err(ApiPrimitiveError::Unknown),
165        }
166    }
167}
168/// `GraphQL` type kind labels.
169#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
170pub enum GraphqlTypeKind {
171    /// A stable label variant.
172    Scalar,
173    /// A stable label variant.
174    Object,
175    /// A stable label variant.
176    Interface,
177    /// A stable label variant.
178    Union,
179    /// A stable label variant.
180    Enum,
181    /// A stable label variant.
182    InputObject,
183    /// A stable label variant.
184    List,
185    /// A stable label variant.
186    NonNull,
187}
188
189impl GraphqlTypeKind {
190    /// Returns the stable label.
191    #[must_use]
192    pub const fn as_str(self) -> &'static str {
193        match self {
194            Self::Scalar => "scalar",
195            Self::Object => "object",
196            Self::Interface => "interface",
197            Self::Union => "union",
198            Self::Enum => "enum",
199            Self::InputObject => "input-object",
200            Self::List => "list",
201            Self::NonNull => "non-null",
202        }
203    }
204}
205
206impl Default for GraphqlTypeKind {
207    fn default() -> Self {
208        Self::Scalar
209    }
210}
211
212impl fmt::Display for GraphqlTypeKind {
213    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
214        formatter.write_str(self.as_str())
215    }
216}
217
218impl FromStr for GraphqlTypeKind {
219    type Err = ApiPrimitiveError;
220
221    fn from_str(value: &str) -> Result<Self, Self::Err> {
222        let trimmed = value.trim();
223        if trimmed.is_empty() {
224            return Err(ApiPrimitiveError::Empty);
225        }
226        let normalized = trimmed.to_ascii_lowercase().replace('_', "-");
227        match normalized.as_str() {
228            "scalar" => Ok(Self::Scalar),
229            "object" => Ok(Self::Object),
230            "interface" => Ok(Self::Interface),
231            "union" => Ok(Self::Union),
232            "enum" => Ok(Self::Enum),
233            "input-object" => Ok(Self::InputObject),
234            "list" => Ok(Self::List),
235            "non-null" => Ok(Self::NonNull),
236            _ => Err(ApiPrimitiveError::Unknown),
237        }
238    }
239}
240
241/// Lightweight metadata tying this crate's primary text and label together.
242#[derive(Clone, Debug, Eq, PartialEq)]
243pub struct PrimitiveMetadata {
244    name: GraphqlName,
245    kind: GraphqlOperationKind,
246}
247
248impl PrimitiveMetadata {
249    /// Creates primitive metadata.
250    #[must_use]
251    pub const fn new(name: GraphqlName, kind: GraphqlOperationKind) -> Self {
252        Self { name, kind }
253    }
254
255    /// Returns the primary text value.
256    #[must_use]
257    pub const fn name(&self) -> &GraphqlName {
258        &self.name
259    }
260
261    /// Returns the primary label.
262    #[must_use]
263    pub const fn kind(&self) -> GraphqlOperationKind {
264        self.kind
265    }
266}
267
268#[cfg(test)]
269mod tests {
270    use super::*;
271
272    #[test]
273    fn parses_and_displays_text() -> Result<(), ApiPrimitiveError> {
274        let value = GraphqlName::new("viewer")?;
275
276        assert_eq!(value.as_str(), "viewer");
277        assert_eq!(value.to_string(), "viewer");
278        assert_eq!("viewer".parse::<GraphqlName>()?, value);
279        Ok(())
280    }
281
282    #[test]
283    fn rejects_empty_text() {
284        assert_eq!(GraphqlName::new(""), Err(ApiPrimitiveError::Empty));
285    }
286
287    #[test]
288    fn parses_and_displays_labels() -> Result<(), ApiPrimitiveError> {
289        let kind = "query".parse::<GraphqlOperationKind>()?;
290
291        assert_eq!(kind, GraphqlOperationKind::Query);
292        assert_eq!(kind.to_string(), "query");
293        Ok(())
294    }
295
296    #[test]
297    fn creates_metadata() -> Result<(), ApiPrimitiveError> {
298        let metadata =
299            PrimitiveMetadata::new(GraphqlName::new("viewer")?, GraphqlOperationKind::default());
300
301        assert_eq!(metadata.name().as_str(), "viewer");
302        assert_eq!(metadata.kind(), GraphqlOperationKind::default());
303        Ok(())
304    }
305}