use gql::{GraphQLError, Response};
use serde_json::{Value, json};
pub type GraphQLResponse = Response;
pub trait ResponseExt {
fn to_json(&self) -> Value;
fn to_json_string(&self) -> String;
fn to_json_bytes(&self) -> Vec<u8>;
}
impl ResponseExt for Response {
fn to_json(&self) -> Value {
match serde_json::to_value(self) {
Ok(value) => value,
Err(error) => serialization_error(error),
}
}
fn to_json_string(&self) -> String {
match serde_json::to_string(self) {
Ok(value) => value,
Err(error) => serialization_error(error).to_string(),
}
}
fn to_json_bytes(&self) -> Vec<u8> {
self.to_json_string().into_bytes()
}
}
#[must_use]
pub fn to_json(response: &Response) -> Value {
response.to_json()
}
#[must_use]
pub fn to_json_bytes(response: &Response) -> Vec<u8> {
response.to_json_bytes()
}
#[must_use]
pub fn error_response(message: impl Into<String>) -> Response {
Response::error(GraphQLError::new(message.into()))
}
#[must_use]
pub fn error_json_bytes(message: impl Into<String>) -> Vec<u8> {
error_response(message).to_json_bytes()
}
fn serialization_error(error: serde_json::Error) -> Value {
json!({
"errors": [{
"message": format!("Failed to serialize the GraphQL response: {error}")
}]
})
}