mockql_core/schema/
introspection.rs1use crate::Header;
18use cynic::http::CynicReqwestError;
19use cynic::http::ReqwestExt;
20use cynic_introspection::CapabilitySet;
21use cynic_introspection::IntrospectionQuery;
22use cynic_introspection::SchemaError;
23use cynic_introspection::SpecificationVersion;
24use reqwest::Client;
25use reqwest::StatusCode;
26use reqwest::Url;
27use reqwest::header::HeaderMap;
28
29pub async fn load_schema_with_introspection(
31 url: &Url,
32 headers: &[Header],
33 client: &Client,
34) -> Result<String, IntrospectionError> {
35 let introspection_result =
36 match execute_instrospection_query(url, headers, client, SpecificationVersion::October2021.capabilities()).await {
37 Ok(introspection_result) => introspection_result,
38 Err(IntrospectionError::GraphqlErrors(_)) => {
39 execute_instrospection_query(url, headers, client, SpecificationVersion::June2018.capabilities()).await?
41 }
42 Err(error) => return Err(error),
43 };
44
45 Ok(
46 introspection_result
47 .into_schema()
48 .map_err(IntrospectionError::from)?
49 .to_sdl(),
50 )
51}
52
53pub async fn execute_instrospection_query(
54 url: &Url,
55 headers: &[Header],
56 client: &Client,
57 capability_set: CapabilitySet,
58) -> Result<IntrospectionQuery, IntrospectionError> {
59 let response = client
60 .post(url.clone())
61 .headers(headers.iter().cloned().collect::<HeaderMap>())
62 .run_graphql(IntrospectionQuery::with_capabilities(capability_set))
63 .await
64 .map_err(IntrospectionError::from)?;
65
66 if let Some(errors) = response.errors {
67 return Err(IntrospectionError::GraphqlErrors(format!("{errors:?}")));
68 }
69
70 response.data.ok_or(IntrospectionError::MissingSchema)
71}
72
73#[derive(Debug, thiserror::Error)]
75pub enum IntrospectionError {
76 #[error("introspection request failed: {0}")]
78 Request(#[source] reqwest::Error),
79 #[error("introspection request returned HTTP status: {status}, body: {body}")]
81 HttpStatus {
82 status: StatusCode,
84 body: String,
86 },
87 #[error("introspection response was not valid JSON: {0}")]
89 Json(#[source] serde_json::Error),
90 #[error("introspection response did not contain a schema")]
92 MissingSchema,
93 #[error("introspection response contained GraphQL errors: {0}")]
95 GraphqlErrors(String),
96 #[error("failed to convert introspection response: {0}")]
98 Conversion(String),
99 #[error("failed to build Apollo schema: {0}")]
101 Schema(String),
102}
103
104impl From<CynicReqwestError> for IntrospectionError {
105 fn from(error: CynicReqwestError) -> Self {
106 match error {
107 CynicReqwestError::ReqwestError(error) => Self::Request(error),
108 CynicReqwestError::ErrorResponse(status, body) => Self::HttpStatus { status, body },
109 }
110 }
111}
112
113impl From<SchemaError> for IntrospectionError {
114 fn from(error: SchemaError) -> Self {
115 match error {
116 SchemaError::IntrospectionQueryFailed => Self::MissingSchema,
117 _ => Self::Conversion(error.to_string()),
118 }
119 }
120}