Skip to main content

deployment_changelog/api/
graphql.rs

1//! # deployment_changelog::api::rest::graphql
2//!
3//! This module provides a `GraphQLClient` for communicating with a GraphQL API endpoint.
4//!
5//! It leverages the `RestClient` implementation from the `deployment_changelog::api::rest` module to handle
6//! HTTP requests and responses, and the `graphql_client` crate to provide type-safe GraphQL query execution.
7//!
8//! The `GraphQLClient` struct provides a simple interface for executing GraphQL queries and
9//! handling their responses. It can be initialized with a base URL and supports executing queries
10//! using the `post` method.
11//!
12//! # Example
13//!
14//! Below is an example of how to use the `GraphQLClient` to execute a query:
15//!
16//! ```rust
17//! use anyhow::Result;
18//! use deployment_changelog::api::rest::graphql::GraphQLClient;
19//! use graphql_client::{GraphQLQuery, Response};
20//!
21//! // Define a query using the graphql_client macro.
22//! #[derive(GraphQLQuery)]
23//! #[graphql(
24//!     schema_path = "path/to/schema.graphql",
25//!     query_path = "path/to/query.graphql",
26//!     response_derives = "Debug"
27//! )]
28//! struct MyQuery;
29//!
30//! async fn execute_query() -> Result<Response<MyQuery::ResponseData>> {
31//!     // Create a new GraphQLClient instance.
32//!     let graphql_client = GraphQLClient::new("https://api.example.com")?;
33//!
34//!     // Set the query variables.
35//!     let variables = MyQuery::Variables { /* ... */ };
36//!
37//!     // Execute the query and return the result.
38//!     graphql_client.post(variables).await
39//! }
40//! ```
41//!
42//! # Errors
43//!
44//! Errors are handled using the `anyhow` crate, and the `Result` type is used to return errors from
45//! functions. The `post` method can return errors related to HTTP requests, response handling, or
46//! GraphQL-specific issues.
47//!
48//! For more detailed examples and further documentation, please refer to the individual struct and method
49//! documentation.
50use anyhow::{Context, Result};
51use graphql_client::{GraphQLQuery, QueryBody, Response};
52
53use super::rest::RestClient;
54
55const GRAPHQL_ENDPOINT: &str = "graphql";
56
57/// A GraphQL client for communicating with a GraphQL API endpoint.
58///
59/// `GraphQLClient` provides an easy way to execute GraphQL queries and handle their responses.
60/// It is built on top of the `RestClient` from the `deployment_changelog::api::rest` module to handle
61/// HTTP requests and uses the `graphql_client` crate for type-safe query execution.
62///
63/// # Example
64///
65/// Below is an example of how to use the `GraphQLClient` to execute a query:
66///
67/// ```rust
68/// use anyhow::Result;
69/// use deployment_changelog::api::rest::graphql::GraphQLClient;
70/// use graphql_client::{GraphQLQuery, Response};
71///
72/// // Define a query using the graphql_client macro.
73/// #[derive(GraphQLQuery)]
74/// #[graphql(
75///     schema_path = "path/to/schema.graphql",
76///     query_path = "path/to/query.graphql",
77///     response_derives = "Debug"
78/// )]
79/// struct MyQuery;
80///
81/// async fn execute_query() -> Result<Response<MyQuery::ResponseData>> {
82///     // Create a new GraphQLClient instance.
83///     let graphql_client = GraphQLClient::new("https://api.example.com")?;
84///
85///     // Set the query variables.
86///     let variables = MyQuery::Variables { /* ... */ };
87///
88///     // Execute the query and return the result.
89///     graphql_client.post(variables).await
90/// }
91/// ```
92///
93/// # Errors
94///
95/// Errors are handled using the `anyhow` crate, and the `Result` type is used to return errors
96/// from functions. The `post` method can return errors related to HTTP requests, response
97/// handling, or GraphQL-specific issues.
98#[derive(Debug)]
99pub struct GraphQLClient {
100    client: RestClient
101}
102
103impl GraphQLClient {
104    /// Creates a new `GraphQLClient` instance with the given base URL.
105    ///
106    /// The base URL is the root URL of the API server, without any path components.
107    /// The client will append the GraphQL endpoint path to this base URL.
108    ///
109    /// # Example
110    ///
111    /// ```
112    /// use deployment_changelog::api::rest::graphql::GraphQLClient;
113    ///
114    /// let graphql_client = GraphQLClient::new("https://api.example.com")?;
115    /// ```
116    ///
117    /// # Errors
118    ///
119    /// Returns an error if the base URL cannot be parsed or if there is an error
120    /// creating the underlying `RestClient`.
121    pub fn new(base_url: &str) -> Result<Self> {
122        Ok(Self {
123            client: RestClient::new(base_url)?
124        })
125    }
126
127    /// Creates a new `GraphQLClient` instance using an existing `RestClient`.
128    ///
129    /// This method can be useful if you want to share a single `RestClient` instance
130    /// between multiple clients, or if you need to customize the `RestClient` before
131    /// passing it to the `GraphQLClient`.
132    ///
133    /// # Example
134    ///
135    /// ```
136    /// use deployment_changelog::api::rest::{graphql::GraphQLClient, RestClient};
137    ///
138    /// let rest_client = RestClient::new("https://api.example.com")?;
139    /// let graphql_client = GraphQLClient::from_client(rest_client);
140    /// ```
141    pub fn from_client(client: RestClient) -> Self {
142        Self {
143            client
144        }
145    }
146
147    /// Executes a GraphQL query with the given variables and returns the response.
148    ///
149    /// The query is defined using the `GraphQLQuery` trait from the `graphql_client` crate.
150    /// This method takes the variables required by the query and returns a `Response`
151    /// containing the parsed response data or an error if the request fails.
152    ///
153    /// # Example
154    ///
155    /// ```
156    /// use deployment_changelog::api::rest::graphql::GraphQLClient;
157    /// use graphql_client::{GraphQLQuery, Response};
158    ///
159    /// #[derive(GraphQLQuery)]
160    /// #[graphql(
161    ///     schema_path = "path/to/schema.graphql",
162    ///     query_path = "path/to/query.graphql",
163    ///     response_derives = "Debug"
164    /// )]
165    /// struct MyQuery;
166    ///
167    /// async fn execute_query() -> Result<Response<MyQuery::ResponseData>> {
168    ///     let graphql_client = GraphQLClient::new("https://api.example.com")?;
169    ///     let variables = MyQuery::Variables { /* ... */ };
170    ///     graphql_client.post(variables).await
171    /// }
172    /// ```
173    ///
174    /// # Errors
175    ///
176    /// Returns an error if there is an issue with the HTTP request, response handling,
177    /// or if the GraphQL API returns an error.
178    pub async fn post<Q: GraphQLQuery>(&self, variables: Q::Variables) -> Result<Response<Q::ResponseData>> {
179        let body = Q::build_query(variables);
180        self.client.post_json::<Response<Q::ResponseData>, QueryBody<Q::Variables>>(GRAPHQL_ENDPOINT, &body)
181            .await
182            .with_context(|| {
183                match serde_json::to_string_pretty(&body) {
184                    Ok(body_serialized) => format!("Error making GraphQL call with query {0}", body_serialized),
185                    Err(error) => format!("Error serializing GraphQL body: {error}")
186                }
187            })
188    }
189}
190