mockql_core/schema/
mod.rs1mod introspection;
18
19use crate::Header;
20use apollo_compiler::Schema;
21use apollo_compiler::ast::Definition;
22use apollo_compiler::ast::Document;
23use apollo_compiler::validation::Valid;
24use apollo_compiler::validation::WithErrors;
25pub use introspection::IntrospectionError;
26pub use introspection::load_schema_with_introspection;
27use reqwest::Client;
28use reqwest::Url;
29use std::path::Path;
30use std::sync::LazyLock;
31
32static MOCK_DIRECTIVE_DEFINITION: LazyLock<Document> = LazyLock::new(|| {
33 Document::parse(
34 "directive @mock(hint: String) on QUERY | MUTATION | FIELD",
35 "mock-directive.graphql",
36 )
37 .expect("built-in @mock directive definition should parse")
38});
39
40#[derive(Debug, thiserror::Error)]
42pub enum SchemaLoadError {
43 #[error("failed to read schema file: {0}")]
45 Io(#[from] std::io::Error),
46 #[error("failed to parse schema: {0:?}")]
48 Parse(Vec<String>),
49 #[error("failed to validate schema: {0:?}")]
51 Validate(Vec<String>),
52 #[error("missing GraphQL URL for schema introspection")]
54 MissingGraphQLUrl,
55 #[error(transparent)]
57 Introspection(#[from] IntrospectionError),
58}
59
60pub async fn load_schema(
62 schema_path: Option<&Path>,
63 graphql_url: Option<&Url>,
64 graphql_headers: &[Header],
65 client: &Client,
66) -> Result<Valid<Schema>, SchemaLoadError> {
67 let sdl = match schema_path {
68 Some(path) => std::fs::read_to_string(path)?,
69 None => {
70 load_schema_with_introspection(
71 graphql_url.ok_or(SchemaLoadError::MissingGraphQLUrl)?,
72 graphql_headers,
73 client,
74 )
75 .await?
76 }
77 };
78 to_schema_with_mock_directive(&sdl)
79}
80
81pub fn to_schema_with_mock_directive(sdl: &str) -> Result<Valid<Schema>, SchemaLoadError> {
83 let document = Document::parse(sdl, "schema.graphql").map_err(|e| SchemaLoadError::Parse(collect_errors(e)))?;
84
85 let builder = Schema::builder().add_ast(&document);
86 let builder = if document
87 .definitions
88 .iter()
89 .any(|definition| matches!(definition, Definition::DirectiveDefinition(d) if d.name.as_str() == "mock"))
90 {
91 builder
92 } else {
93 builder.add_ast(&MOCK_DIRECTIVE_DEFINITION)
94 };
95
96 builder
97 .build()
98 .map_err(|e| SchemaLoadError::Parse(collect_errors(e)))?
99 .validate()
100 .map_err(|e| SchemaLoadError::Validate(collect_errors(e)))
101}
102
103fn collect_errors<T>(errors: WithErrors<T>) -> Vec<String> {
104 errors.errors.iter().map(|d| d.error.to_string()).collect()
105}
106
107#[cfg(test)]
108mod tests {
109 use super::*;
110
111 #[test]
112 fn instrument_schema_adds_mock_directive_when_missing() {
113 let schema = to_schema_with_mock_directive("type Query { hello: String }").expect("schema should instrument");
114 let directive = schema
115 .directive_definitions
116 .get("mock")
117 .expect("@mock directive should be present");
118
119 assert_eq!(
120 directive.serialize().to_string(),
121 "directive @mock(hint: String) on QUERY | MUTATION | FIELD"
122 );
123 }
124
125 #[test]
126 fn instrument_schema_leaves_existing_mock_directive_unchanged() {
127 let schema = to_schema_with_mock_directive(
128 r"
129 directive @mock(hint: String) on QUERY | MUTATION | FIELD
130 type Query { hello: String }
131 ",
132 )
133 .expect("schema should instrument");
134 assert_eq!(
135 schema
136 .directive_definitions
137 .keys()
138 .filter(|name| name.as_str() == "mock")
139 .count(),
140 1
141 );
142 }
143}