1use apollo_parser::Parser;
7use apollo_parser::cst::CstNode;
8use odk_schema::{
9 CompiledField, CompiledModel, CompiledOperation, CompiledSchema, CompiledType, CompiledUnion,
10 CompiledUnionVariant, Directive, Extensions, FieldSelection, FragmentDefinition,
11 FragmentSpread, InlineFragment, LiteralValue, OperationKind, ScalarType, SelectionSet,
12 Variable,
13};
14
15#[derive(Debug)]
17pub enum GraphqlLoadError {
18 Io(std::io::Error),
19 Parse(Vec<String>),
20 Validation(String),
21}
22
23impl std::fmt::Display for GraphqlLoadError {
24 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
25 match self {
26 GraphqlLoadError::Io(e) => write!(f, "IO error: {}", e),
27 GraphqlLoadError::Parse(errors) => {
28 write!(f, "GraphQL parse errors: {}", errors.join("; "))
29 }
30 GraphqlLoadError::Validation(msg) => write!(f, "Validation error: {}", msg),
31 }
32 }
33}
34
35impl std::error::Error for GraphqlLoadError {}
36
37impl From<std::io::Error> for GraphqlLoadError {
38 fn from(e: std::io::Error) -> Self {
39 GraphqlLoadError::Io(e)
40 }
41}
42
43fn map_graphql_scalar(name: &str) -> Option<CompiledType> {
45 match name {
46 "String" => Some(CompiledType::Scalar {
47 name: ScalarType::String,
48 }),
49 "Int" => Some(CompiledType::Scalar {
50 name: ScalarType::Int32,
51 }),
52 "Float" => Some(CompiledType::Scalar {
53 name: ScalarType::Float64,
54 }),
55 "Boolean" => Some(CompiledType::Scalar {
56 name: ScalarType::Boolean,
57 }),
58 "ID" => {
59 Some(CompiledType::Scalar {
61 name: ScalarType::String,
62 })
63 }
64 _ => None,
65 }
66}
67
68pub fn map_graphql_type(ty: &apollo_parser::cst::Type) -> (CompiledType, bool) {
75 use apollo_parser::cst::Type;
76
77 match ty {
78 Type::NamedType(named) => {
79 let name = named
80 .name()
81 .map(|n| n.text().to_string())
82 .unwrap_or_default();
83 let compiled = map_graphql_scalar(&name).unwrap_or_else(|| CompiledType::Ref { name });
84 (compiled, true)
86 }
87 Type::ListType(list) => {
88 if let Some(inner) = list.ty() {
89 let (inner_type, _inner_nullable) = map_graphql_type(&inner);
90 (
91 CompiledType::Array {
92 items: Box::new(inner_type),
93 length: None,
94 },
95 true,
96 )
97 } else {
98 (
99 CompiledType::Scalar {
100 name: ScalarType::Unknown,
101 },
102 true,
103 )
104 }
105 }
106 Type::NonNullType(non_null) => {
107 if let Some(named) = non_null.named_type() {
108 let name = named
109 .name()
110 .map(|n| n.text().to_string())
111 .unwrap_or_default();
112 let compiled =
113 map_graphql_scalar(&name).unwrap_or_else(|| CompiledType::Ref { name });
114 (compiled, false)
115 } else if let Some(list) = non_null.list_type() {
116 if let Some(inner) = list.ty() {
117 let (inner_type, _) = map_graphql_type(&inner);
118 (
119 CompiledType::Array {
120 items: Box::new(inner_type),
121 length: None,
122 },
123 false,
124 )
125 } else {
126 (
127 CompiledType::Scalar {
128 name: ScalarType::Unknown,
129 },
130 false,
131 )
132 }
133 } else {
134 (
135 CompiledType::Scalar {
136 name: ScalarType::Unknown,
137 },
138 false,
139 )
140 }
141 }
142 }
143}
144
145pub fn load_graphql_schema(path: &std::path::Path) -> Result<CompiledSchema, GraphqlLoadError> {
147 let content = std::fs::read_to_string(path)?;
148 let file_name = path.to_string_lossy().to_string();
149 parse_graphql_sdl(&content, &file_name)
150}
151
152pub fn parse_graphql_sdl(
154 source: &str,
155 file_name: &str,
156) -> Result<CompiledSchema, GraphqlLoadError> {
157 let parser = Parser::new(source);
158 let cst = parser.parse();
159
160 let errors: Vec<String> = cst.errors().map(|e| e.message().to_string()).collect();
162 if !errors.is_empty() {
163 return Err(GraphqlLoadError::Parse(errors));
164 }
165
166 let doc = cst.document();
167
168 let schema_name = std::path::Path::new(file_name)
170 .file_stem()
171 .and_then(|s| s.to_str())
172 .unwrap_or("Schema")
173 .to_string();
174
175 let mut schema = CompiledSchema::new(&schema_name);
176
177 for def in doc.definitions() {
178 use apollo_parser::cst::Definition;
179
180 match def {
181 Definition::ObjectTypeDefinition(obj) => {
182 let model = convert_object_type(&obj)?;
183 schema.add_model(model);
184 }
185 Definition::InputObjectTypeDefinition(input) => {
186 let model = convert_input_type(&input)?;
187 schema.add_model(model);
188 }
189 Definition::InterfaceTypeDefinition(iface) => {
190 let model = convert_interface_type(&iface)?;
191 schema.add_model(model);
192 }
193 Definition::EnumTypeDefinition(en) => {
194 let union = convert_enum_type(&en)?;
195 schema.add_union(union);
196 }
197 Definition::UnionTypeDefinition(un) => {
198 let union = convert_union_type(&un)?;
199 schema.add_union(union);
200 }
201 Definition::ScalarTypeDefinition(sc) => {
202 let name = sc.name().map(|n| n.text().to_string()).unwrap_or_default();
205 let description = sc.description().and_then(|d| {
206 d.string_value()
207 .map(|s| s.source_string().trim_matches('"').to_string())
208 });
209 let mut model = CompiledModel::new(&name);
210 model.description = description;
211 model
212 .extensions
213 .add_unknown("graphql_custom_scalar".to_string(), serde_json::json!(true));
214 schema.add_model(model);
215 }
216 _ => {}
218 }
219 }
220
221 Ok(schema)
222}
223
224fn convert_object_type(
226 obj: &apollo_parser::cst::ObjectTypeDefinition,
227) -> Result<CompiledModel, GraphqlLoadError> {
228 let name = obj.name().map(|n| n.text().to_string()).unwrap_or_default();
229 let description = obj.description().and_then(|d| {
230 d.string_value()
231 .map(|s| s.source_string().trim_matches('"').to_string())
232 });
233
234 let mut model = CompiledModel::new(&name);
235 model.description = description;
236
237 if let Some(impls) = obj.implements_interfaces() {
239 let interfaces: Vec<String> = impls
240 .named_types()
241 .filter_map(|n| n.name().map(|name| name.text().to_string()))
242 .collect();
243 if !interfaces.is_empty() {
244 model.extensions.add_unknown(
245 "graphql_implements".to_string(),
246 serde_json::json!(interfaces),
247 );
248 }
249 }
250
251 if let Some(fields_def) = obj.fields_definition() {
252 for field_def in fields_def.field_definitions() {
253 let field = convert_field_definition(&field_def)?;
254 model.add_field(field);
255 }
256 }
257
258 Ok(model)
259}
260
261fn convert_input_type(
263 input: &apollo_parser::cst::InputObjectTypeDefinition,
264) -> Result<CompiledModel, GraphqlLoadError> {
265 let name = input
266 .name()
267 .map(|n| n.text().to_string())
268 .unwrap_or_default();
269 let description = input.description().and_then(|d| {
270 d.string_value()
271 .map(|s| s.source_string().trim_matches('"').to_string())
272 });
273
274 let mut model = CompiledModel::new(&name);
275 model.description = description;
276 model
277 .extensions
278 .add_unknown("graphql_input".to_string(), serde_json::json!(true));
279
280 if let Some(fields_def) = input.input_fields_definition() {
281 for input_val in fields_def.input_value_definitions() {
282 let field_name = input_val
283 .name()
284 .map(|n| n.text().to_string())
285 .unwrap_or_default();
286 let field_desc = input_val.description().and_then(|d| {
287 d.string_value()
288 .map(|s| s.source_string().trim_matches('"').to_string())
289 });
290
291 if let Some(ty) = input_val.ty() {
292 let (compiled_type, nullable) = map_graphql_type(&ty);
293 let mut field = CompiledField::new(&field_name, compiled_type);
294 if nullable {
295 field.optional = Some(true);
296 }
297 field.description = field_desc;
298 model.add_field(field);
299 }
300 }
301 }
302
303 Ok(model)
304}
305
306fn convert_interface_type(
308 iface: &apollo_parser::cst::InterfaceTypeDefinition,
309) -> Result<CompiledModel, GraphqlLoadError> {
310 let name = iface
311 .name()
312 .map(|n| n.text().to_string())
313 .unwrap_or_default();
314 let description = iface.description().and_then(|d| {
315 d.string_value()
316 .map(|s| s.source_string().trim_matches('"').to_string())
317 });
318
319 let mut model = CompiledModel::new(&name);
320 model.description = description;
321 model
322 .extensions
323 .add_unknown("graphql_interface".to_string(), serde_json::json!(true));
324
325 if let Some(fields_def) = iface.fields_definition() {
326 for field_def in fields_def.field_definitions() {
327 let field = convert_field_definition(&field_def)?;
328 model.add_field(field);
329 }
330 }
331
332 Ok(model)
333}
334
335fn convert_field_definition(
337 field_def: &apollo_parser::cst::FieldDefinition,
338) -> Result<CompiledField, GraphqlLoadError> {
339 let name = field_def
340 .name()
341 .map(|n| n.text().to_string())
342 .unwrap_or_default();
343 let description = field_def.description().and_then(|d| {
344 d.string_value()
345 .map(|s| s.source_string().trim_matches('"').to_string())
346 });
347
348 let (compiled_type, nullable) = if let Some(ty) = field_def.ty() {
349 map_graphql_type(&ty)
350 } else {
351 (
352 CompiledType::Scalar {
353 name: ScalarType::Unknown,
354 },
355 true,
356 )
357 };
358
359 let mut field = CompiledField::new(&name, compiled_type);
360 if nullable {
361 field.optional = Some(true);
362 }
363 field.description = description;
364
365 if let Some(args_def) = field_def.arguments_definition() {
367 let args: Vec<serde_json::Value> = args_def
368 .input_value_definitions()
369 .filter_map(|arg| {
370 let arg_name = arg.name().map(|n| n.text().to_string())?;
371 let arg_type = arg.ty().map(|t| format!("{}", t.source_string()))?;
372 Some(serde_json::json!({
373 "name": arg_name,
374 "type": arg_type,
375 }))
376 })
377 .collect();
378 if !args.is_empty() {
379 field
380 .extensions
381 .add_unknown("graphql_arguments".to_string(), serde_json::json!(args));
382 }
383 }
384
385 Ok(field)
386}
387
388fn convert_enum_type(
390 en: &apollo_parser::cst::EnumTypeDefinition,
391) -> Result<CompiledUnion, GraphqlLoadError> {
392 let name = en.name().map(|n| n.text().to_string()).unwrap_or_default();
393 let description = en.description().and_then(|d| {
394 d.string_value()
395 .map(|s| s.source_string().trim_matches('"').to_string())
396 });
397
398 let mut variants = Vec::new();
399 if let Some(vals) = en.enum_values_definition() {
400 for val in vals.enum_value_definitions() {
401 let val_name = val
402 .enum_value()
403 .map(|v| v.name().map(|n| n.text().to_string()).unwrap_or_default())
404 .unwrap_or_default();
405 variants.push(CompiledUnionVariant {
406 name: val_name.clone(),
407 variant_type: Some(CompiledType::Literal {
408 value: LiteralValue::String(val_name),
409 }),
410 });
411 }
412 }
413
414 Ok(CompiledUnion {
415 name,
416 variants,
417 tag: None,
418 rename_all: None,
419 description,
420 extensions: Extensions::default(),
421 source: None,
422 })
423}
424
425fn convert_union_type(
427 un: &apollo_parser::cst::UnionTypeDefinition,
428) -> Result<CompiledUnion, GraphqlLoadError> {
429 let name = un.name().map(|n| n.text().to_string()).unwrap_or_default();
430 let description = un.description().and_then(|d| {
431 d.string_value()
432 .map(|s| s.source_string().trim_matches('"').to_string())
433 });
434
435 let mut variants = Vec::new();
436 if let Some(members) = un.union_member_types() {
437 for member in members.named_types() {
438 let member_name = member
439 .name()
440 .map(|n| n.text().to_string())
441 .unwrap_or_default();
442 variants.push(CompiledUnionVariant {
443 name: member_name.clone(),
444 variant_type: Some(CompiledType::Ref { name: member_name }),
445 });
446 }
447 }
448
449 Ok(CompiledUnion {
450 name,
451 variants,
452 tag: None,
453 rename_all: None,
454 description,
455 extensions: Extensions::default(),
456 source: None,
457 })
458}
459
460pub fn load_graphql_operations(
465 pattern: &str,
466) -> Result<(Vec<CompiledOperation>, Vec<FragmentDefinition>), GraphqlLoadError> {
467 let paths = glob::glob(pattern).map_err(|e| {
468 GraphqlLoadError::Validation(format!("Invalid glob pattern '{}': {}", pattern, e))
469 })?;
470
471 let mut operations = Vec::new();
472 let mut fragments = Vec::new();
473
474 for entry in paths {
475 let path = entry.map_err(|e| GraphqlLoadError::Io(e.into_error()))?;
476 let content = std::fs::read_to_string(&path)?;
477 let (mut ops, mut frags) = parse_graphql_operations(&content, &path.to_string_lossy())?;
478 operations.append(&mut ops);
479 fragments.append(&mut frags);
480 }
481
482 Ok((operations, fragments))
483}
484
485pub fn parse_graphql_operations(
487 source: &str,
488 file_name: &str,
489) -> Result<(Vec<CompiledOperation>, Vec<FragmentDefinition>), GraphqlLoadError> {
490 let parser = Parser::new(source);
491 let cst = parser.parse();
492
493 let errors: Vec<String> = cst.errors().map(|e| e.message().to_string()).collect();
494 if !errors.is_empty() {
495 return Err(GraphqlLoadError::Parse(errors));
496 }
497
498 let doc = cst.document();
499 let mut operations = Vec::new();
500 let mut fragments = Vec::new();
501
502 for def in doc.definitions() {
503 use apollo_parser::cst::Definition;
504
505 match def {
506 Definition::OperationDefinition(op_def) => {
507 let op = convert_operation(&op_def, file_name)?;
508 operations.push(op);
509 }
510 Definition::FragmentDefinition(frag_def) => {
511 let frag = convert_fragment_definition(&frag_def)?;
512 fragments.push(frag);
513 }
514 _ => {
515 }
518 }
519 }
520
521 Ok((operations, fragments))
522}
523
524fn convert_operation(
526 op_def: &apollo_parser::cst::OperationDefinition,
527 _file_name: &str,
528) -> Result<CompiledOperation, GraphqlLoadError> {
529 let kind = match op_def.operation_type() {
531 Some(op_type) => {
532 if op_type.query_token().is_some() {
533 OperationKind::Query
534 } else if op_type.mutation_token().is_some() {
535 OperationKind::Mutation
536 } else if op_type.subscription_token().is_some() {
537 OperationKind::Subscription
538 } else {
539 OperationKind::Query
540 }
541 }
542 None => OperationKind::Query, };
544
545 let name = op_def
547 .name()
548 .map(|n| n.text().to_string())
549 .unwrap_or_else(|| "Anonymous".to_string());
550
551 let variables = if let Some(var_defs) = op_def.variable_definitions() {
553 var_defs
554 .variable_definitions()
555 .filter_map(|var_def| {
556 let var_name = var_def
557 .variable()
558 .and_then(|v| v.name())
559 .map(|n| n.text().to_string())?;
560 let (var_type, nullable) =
561 var_def.ty().map(|ty| map_graphql_type(&ty)).unwrap_or((
562 CompiledType::Scalar {
563 name: ScalarType::Unknown,
564 },
565 true,
566 ));
567 Some(Variable {
568 name: var_name,
569 variable_type: var_type,
570 required: !nullable,
571 default_value: var_def.default_value().map(|_| serde_json::json!(null)),
572 description: None,
573 })
574 })
575 .collect()
576 } else {
577 vec![]
578 };
579
580 let selection = op_def
582 .selection_set()
583 .map(|sel| convert_selection_set(&sel));
584
585 let directives = op_def
587 .directives()
588 .map(|dirs| convert_directives(&dirs))
589 .unwrap_or_default();
590
591 let output = CompiledType::Scalar {
594 name: ScalarType::Unknown,
595 };
596
597 Ok(CompiledOperation {
598 name,
599 kind,
600 input: None,
601 output,
602 variables,
603 selection,
604 description: None,
605 extensions: Extensions::default(),
606 directives,
607 })
608}
609
610fn convert_selection_set(sel_set: &apollo_parser::cst::SelectionSet) -> SelectionSet {
612 let mut fields = Vec::new();
613 let mut fragment_spreads = Vec::new();
614 let mut inline_fragments = Vec::new();
615
616 for selection in sel_set.selections() {
617 use apollo_parser::cst::Selection;
618
619 match selection {
620 Selection::Field(field) => {
621 let name = field
622 .name()
623 .map(|n| n.text().to_string())
624 .unwrap_or_default();
625 let alias = field
626 .alias()
627 .and_then(|a| a.name().map(|n| n.text().to_string()));
628
629 let arguments: Vec<(String, CompiledType)> = field
630 .arguments()
631 .map(|args| {
632 args.arguments()
633 .filter_map(|arg| {
634 let arg_name = arg.name().map(|n| n.text().to_string())?;
635 Some((
638 arg_name,
639 CompiledType::Scalar {
640 name: ScalarType::Unknown,
641 },
642 ))
643 })
644 .collect()
645 })
646 .unwrap_or_default();
647
648 let nested = field.selection_set().map(|s| convert_selection_set(&s));
649
650 let directives = field
651 .directives()
652 .map(|dirs| convert_directives(&dirs))
653 .unwrap_or_default();
654
655 fields.push(FieldSelection {
656 name,
657 alias,
658 arguments,
659 selection: nested,
660 directives,
661 });
662 }
663 Selection::FragmentSpread(spread) => {
664 let name = spread
665 .fragment_name()
666 .and_then(|n| n.name())
667 .map(|n| n.text().to_string())
668 .unwrap_or_default();
669 let directives = spread
670 .directives()
671 .map(|dirs| convert_directives(&dirs))
672 .unwrap_or_default();
673 fragment_spreads.push(FragmentSpread { name, directives });
674 }
675 Selection::InlineFragment(inline) => {
676 let type_condition = inline
677 .type_condition()
678 .and_then(|tc| tc.named_type())
679 .and_then(|nt| nt.name())
680 .map(|n| n.text().to_string());
681 let selection = inline
682 .selection_set()
683 .map(|s| convert_selection_set(&s))
684 .unwrap_or(SelectionSet {
685 fields: vec![],
686 fragment_spreads: vec![],
687 inline_fragments: vec![],
688 });
689 let directives = inline
690 .directives()
691 .map(|dirs| convert_directives(&dirs))
692 .unwrap_or_default();
693 inline_fragments.push(InlineFragment {
694 type_condition,
695 selection,
696 directives,
697 });
698 }
699 }
700 }
701
702 SelectionSet {
703 fields,
704 fragment_spreads,
705 inline_fragments,
706 }
707}
708
709fn convert_directives(dirs: &apollo_parser::cst::Directives) -> Vec<Directive> {
711 dirs.directives()
712 .filter_map(|dir| {
713 let name = dir.name().map(|n| n.text().to_string())?;
714 let arguments: Vec<(String, serde_json::Value)> = dir
715 .arguments()
716 .map(|args| {
717 args.arguments()
718 .filter_map(|arg| {
719 let arg_name = arg.name().map(|n| n.text().to_string())?;
720 let value = arg
722 .value()
723 .map(|v| serde_json::json!(v.source_string()))
724 .unwrap_or(serde_json::json!(null));
725 Some((arg_name, value))
726 })
727 .collect()
728 })
729 .unwrap_or_default();
730 Some(Directive { name, arguments })
731 })
732 .collect()
733}
734
735fn convert_fragment_definition(
737 frag: &apollo_parser::cst::FragmentDefinition,
738) -> Result<FragmentDefinition, GraphqlLoadError> {
739 let name = frag
740 .fragment_name()
741 .and_then(|n| n.name())
742 .map(|n| n.text().to_string())
743 .unwrap_or_default();
744
745 let type_condition = frag
746 .type_condition()
747 .and_then(|tc| tc.named_type())
748 .and_then(|nt| nt.name())
749 .map(|n| n.text().to_string())
750 .unwrap_or_default();
751
752 let selection = frag
753 .selection_set()
754 .map(|s| convert_selection_set(&s))
755 .unwrap_or(SelectionSet {
756 fields: vec![],
757 fragment_spreads: vec![],
758 inline_fragments: vec![],
759 });
760
761 let directives = frag
762 .directives()
763 .map(|dirs| convert_directives(&dirs))
764 .unwrap_or_default();
765
766 Ok(FragmentDefinition {
767 name,
768 type_condition,
769 selection,
770 directives,
771 })
772}
773
774#[cfg(test)]
775mod tests {
776 use super::*;
777
778 #[test]
779 fn test_parse_simple_object_type() {
780 let sdl = r#"
781 type User {
782 id: ID!
783 name: String!
784 email: String
785 age: Int
786 }
787 "#;
788
789 let schema = parse_graphql_sdl(sdl, "test.graphql").unwrap();
790 assert_eq!(schema.models.len(), 1);
791
792 let user = &schema.models[0];
793 assert_eq!(user.name, "User");
794 assert_eq!(user.fields.len(), 4);
795
796 let id_field = user.fields.iter().find(|f| f.name == "id").unwrap();
798 assert!(id_field.optional.is_none() || !id_field.optional.unwrap());
799
800 let email_field = user.fields.iter().find(|f| f.name == "email").unwrap();
802 assert_eq!(email_field.optional, Some(true));
803 }
804
805 #[test]
806 fn test_parse_input_type() {
807 let sdl = r#"
808 input CreateUserInput {
809 name: String!
810 email: String!
811 bio: String
812 }
813 "#;
814
815 let schema = parse_graphql_sdl(sdl, "test.graphql").unwrap();
816 assert_eq!(schema.models.len(), 1);
817
818 let input = &schema.models[0];
819 assert_eq!(input.name, "CreateUserInput");
820 assert!(!input.extensions.unknown.is_empty());
821 assert_eq!(
822 input.extensions.unknown.get("graphql_input"),
823 Some(&serde_json::json!(true))
824 );
825 }
826
827 #[test]
828 fn test_parse_enum() {
829 let sdl = r#"
830 enum Status {
831 ACTIVE
832 INACTIVE
833 PENDING
834 }
835 "#;
836
837 let schema = parse_graphql_sdl(sdl, "test.graphql").unwrap();
838 assert_eq!(schema.unions.len(), 1);
839
840 let status = &schema.unions[0];
841 assert_eq!(status.name, "Status");
842 assert_eq!(status.variants.len(), 3);
843 assert_eq!(status.variants[0].name, "ACTIVE");
844 }
845
846 #[test]
847 fn test_parse_union() {
848 let sdl = r#"
849 type Cat { name: String! }
850 type Dog { name: String! }
851 union Animal = Cat | Dog
852 "#;
853
854 let schema = parse_graphql_sdl(sdl, "test.graphql").unwrap();
855 assert_eq!(schema.models.len(), 2);
856 assert_eq!(schema.unions.len(), 1);
857
858 let animal = &schema.unions[0];
859 assert_eq!(animal.name, "Animal");
860 assert_eq!(animal.variants.len(), 2);
861
862 match &animal.variants[0].variant_type {
864 Some(CompiledType::Ref { name }) => assert_eq!(name, "Cat"),
865 other => panic!("Expected Ref variant, got {:?}", other),
866 }
867 }
868
869 #[test]
870 fn test_parse_interface() {
871 let sdl = r#"
872 interface Node {
873 id: ID!
874 }
875 "#;
876
877 let schema = parse_graphql_sdl(sdl, "test.graphql").unwrap();
878 assert_eq!(schema.models.len(), 1);
879
880 let node = &schema.models[0];
881 assert_eq!(node.name, "Node");
882 assert_eq!(
883 node.extensions.unknown.get("graphql_interface"),
884 Some(&serde_json::json!(true))
885 );
886 }
887
888 #[test]
889 fn test_parse_array_types() {
890 let sdl = r#"
891 type User {
892 tags: [String!]!
893 posts: [Post]
894 }
895 "#;
896
897 let schema = parse_graphql_sdl(sdl, "test.graphql").unwrap();
898 let user = &schema.models[0];
899
900 let tags = user.fields.iter().find(|f| f.name == "tags").unwrap();
901 match &tags.field_type {
902 CompiledType::Array { .. } => {}
903 other => panic!("Expected Array type for tags, got {:?}", other),
904 }
905 assert!(tags.optional.is_none() || !tags.optional.unwrap());
907
908 let posts = user.fields.iter().find(|f| f.name == "posts").unwrap();
909 match &posts.field_type {
910 CompiledType::Array { .. } => {}
911 other => panic!("Expected Array type for posts, got {:?}", other),
912 }
913 assert_eq!(posts.optional, Some(true));
915 }
916
917 #[test]
918 fn test_parse_query_operation() {
919 let doc = r#"
920 query GetUser($id: ID!) {
921 user(id: $id) {
922 id
923 name
924 email
925 }
926 }
927 "#;
928
929 let (ops, frags) = parse_graphql_operations(doc, "test.graphql").unwrap();
930 assert_eq!(ops.len(), 1);
931 assert_eq!(frags.len(), 0);
932
933 let op = &ops[0];
934 assert_eq!(op.name, "GetUser");
935 assert!(matches!(op.kind, OperationKind::Query));
936 assert_eq!(op.variables.len(), 1);
937 assert_eq!(op.variables[0].name, "id");
938 assert!(op.variables[0].required);
939
940 let sel = op.selection.as_ref().unwrap();
941 assert_eq!(sel.fields.len(), 1);
942 assert_eq!(sel.fields[0].name, "user");
943
944 let user_sel = sel.fields[0].selection.as_ref().unwrap();
946 assert_eq!(user_sel.fields.len(), 3);
947 }
948
949 #[test]
950 fn test_parse_mutation_operation() {
951 let doc = r#"
952 mutation CreateUser($input: CreateUserInput!) {
953 createUser(input: $input) {
954 id
955 name
956 }
957 }
958 "#;
959
960 let (ops, _) = parse_graphql_operations(doc, "test.graphql").unwrap();
961 assert_eq!(ops.len(), 1);
962
963 let op = &ops[0];
964 assert_eq!(op.name, "CreateUser");
965 assert!(matches!(op.kind, OperationKind::Mutation));
966 }
967
968 #[test]
969 fn test_parse_fragment_definition() {
970 let doc = r#"
971 fragment UserFields on User {
972 id
973 name
974 email
975 }
976
977 query GetUser($id: ID!) {
978 user(id: $id) {
979 ...UserFields
980 }
981 }
982 "#;
983
984 let (ops, frags) = parse_graphql_operations(doc, "test.graphql").unwrap();
985 assert_eq!(ops.len(), 1);
986 assert_eq!(frags.len(), 1);
987
988 let frag = &frags[0];
989 assert_eq!(frag.name, "UserFields");
990 assert_eq!(frag.type_condition, "User");
991 assert_eq!(frag.selection.fields.len(), 3);
992
993 let sel = ops[0].selection.as_ref().unwrap();
995 assert_eq!(sel.fields[0].name, "user");
996 let user_sel = sel.fields[0].selection.as_ref().unwrap();
997 assert_eq!(user_sel.fragment_spreads.len(), 1);
998 assert_eq!(user_sel.fragment_spreads[0].name, "UserFields");
999 }
1000
1001 #[test]
1002 fn test_parse_inline_fragment() {
1003 let doc = r#"
1004 query SearchResults($query: String!) {
1005 search(query: $query) {
1006 ... on User {
1007 name
1008 email
1009 }
1010 ... on Post {
1011 title
1012 body
1013 }
1014 }
1015 }
1016 "#;
1017
1018 let (ops, _) = parse_graphql_operations(doc, "test.graphql").unwrap();
1019 let sel = ops[0].selection.as_ref().unwrap();
1020 let search_sel = sel.fields[0].selection.as_ref().unwrap();
1021 assert_eq!(search_sel.inline_fragments.len(), 2);
1022 assert_eq!(
1023 search_sel.inline_fragments[0].type_condition,
1024 Some("User".to_string())
1025 );
1026 assert_eq!(
1027 search_sel.inline_fragments[1].type_condition,
1028 Some("Post".to_string())
1029 );
1030 }
1031
1032 #[test]
1033 fn test_parse_field_alias() {
1034 let doc = r#"
1035 query GetUsers {
1036 activeUsers: users(status: ACTIVE) {
1037 id
1038 }
1039 }
1040 "#;
1041
1042 let (ops, _) = parse_graphql_operations(doc, "test.graphql").unwrap();
1043 let sel = ops[0].selection.as_ref().unwrap();
1044 assert_eq!(sel.fields[0].alias, Some("activeUsers".to_string()));
1045 assert_eq!(sel.fields[0].name, "users");
1046 }
1047
1048 #[test]
1049 fn test_parse_directive_on_field() {
1050 let doc = r#"
1051 query GetUser($id: ID!, $includeEmail: Boolean!) {
1052 user(id: $id) {
1053 id
1054 email @include(if: $includeEmail)
1055 }
1056 }
1057 "#;
1058
1059 let (ops, _) = parse_graphql_operations(doc, "test.graphql").unwrap();
1060 let sel = ops[0].selection.as_ref().unwrap();
1061 let user_sel = sel.fields[0].selection.as_ref().unwrap();
1062 let email_field = user_sel.fields.iter().find(|f| f.name == "email").unwrap();
1063 assert_eq!(email_field.directives.len(), 1);
1064 assert_eq!(email_field.directives[0].name, "include");
1065 }
1066}