thegraph_graphql_http/
graphql.rs

1//! GraphQL query type and related traits.
2//!
3//! This module contains the [`Document`] type and the [`IntoDocument`] conversion trait. The conversion
4//! trait is implemented for string types: [`String`] and `&str`.
5//!
6
7/// A (raw) GraphQL request document.
8///
9/// This type is a wrapper around a string that represents a GraphQL request document. This type
10/// does not perform any validation on the string.
11#[derive(Debug, Clone, PartialEq, Eq)]
12pub struct Document(String);
13
14impl Document {
15    /// Create a new GraphQL [`Document`] instance from a `String`.
16    pub fn new(value: String) -> Self {
17        Self(value)
18    }
19
20    /// Return a string slice to the document.
21    pub fn as_str(&self) -> &str {
22        &self.0
23    }
24}
25
26impl From<String> for Document {
27    fn from(value: String) -> Self {
28        Self::new(value)
29    }
30}
31
32impl std::fmt::Display for Document {
33    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
34        self.0.fmt(f)
35    }
36}
37
38impl serde::ser::Serialize for Document {
39    fn serialize<S: serde::ser::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
40        self.0.serialize(serializer)
41    }
42}
43
44/// A trait for types that can be converted into a [`Document`].
45pub trait IntoDocument {
46    /// Consumes `self` and returns a [`Document`].
47    fn into_document(self) -> Document;
48}
49
50/// A trait for types that can be converted into a [`Document`] and variables tuple.
51pub trait IntoDocumentWithVariables {
52    type Variables: serde::Serialize;
53
54    /// Consumes `self` and returns a query and variables tuple.
55    fn into_document_with_variables(self) -> (Document, Self::Variables);
56}
57
58impl IntoDocument for Document {
59    fn into_document(self) -> Document {
60        self
61    }
62}
63
64impl IntoDocument for String {
65    fn into_document(self) -> Document {
66        Document(self)
67    }
68}
69
70impl IntoDocument for &str {
71    fn into_document(self) -> Document {
72        Document(self.to_owned())
73    }
74}
75
76impl<T> IntoDocumentWithVariables for T
77where
78    T: IntoDocument,
79{
80    type Variables = ();
81
82    fn into_document_with_variables(self) -> (Document, Self::Variables) {
83        (self.into_document(), ())
84    }
85}