Skip to main content

mockql_core/schema/
mod.rs

1// Copyright 2026 Expedia, Inc.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     https://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Schema loading helpers for file-backed and introspected schemas.
16
17mod 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/// Errors raised while resolving the active GraphQL schema.
41#[derive(Debug, thiserror::Error)]
42pub enum SchemaLoadError {
43  /// Reading a local schema file failed.
44  #[error("failed to read schema file: {0}")]
45  Io(#[from] std::io::Error),
46  /// The schema could not be parsed.
47  #[error("failed to parse schema: {0:?}")]
48  Parse(Vec<String>),
49  /// The schema could not be validated.
50  #[error("failed to validate schema: {0:?}")]
51  Validate(Vec<String>),
52  /// No GraphQL URL was provided for introspection-based schema loading.
53  #[error("missing GraphQL URL for schema introspection")]
54  MissingGraphQLUrl,
55  /// Introspection-based schema loading failed.
56  #[error(transparent)]
57  Introspection(#[from] IntrospectionError),
58}
59
60/// Loads a validated schema from a local SDL file or from introspection.
61pub 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
81/// Parses and validates schema SDL, injecting the built-in `@mock` directive when absent.
82pub 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}