1#![forbid(unsafe_code)]
2#![doc = include_str!("../README.md")]
3
4use core::{fmt, str::FromStr};
5use std::error::Error;
6
7#[derive(Clone, Copy, Debug, Eq, PartialEq)]
9pub enum ApiPrimitiveError {
10 Empty,
12 Invalid,
14 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 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 pub fn parse(value: impl AsRef<str>) -> Result<Self, ApiPrimitiveError> {
62 Self::new(value)
63 }
64
65 #[must_use]
67 pub fn as_str(&self) -> &str {
68 &self.0
69 }
70
71 #[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#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
118pub enum GraphqlOperationKind {
119 Query,
121 Mutation,
123 Subscription,
125}
126
127impl GraphqlOperationKind {
128 #[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#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
170pub enum GraphqlTypeKind {
171 Scalar,
173 Object,
175 Interface,
177 Union,
179 Enum,
181 InputObject,
183 List,
185 NonNull,
187}
188
189impl GraphqlTypeKind {
190 #[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#[derive(Clone, Debug, Eq, PartialEq)]
243pub struct PrimitiveMetadata {
244 name: GraphqlName,
245 kind: GraphqlOperationKind,
246}
247
248impl PrimitiveMetadata {
249 #[must_use]
251 pub const fn new(name: GraphqlName, kind: GraphqlOperationKind) -> Self {
252 Self { name, kind }
253 }
254
255 #[must_use]
257 pub const fn name(&self) -> &GraphqlName {
258 &self.name
259 }
260
261 #[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}