use core::fmt;
use std::{borrow::Cow, sync::Arc};
use smallvec::SmallVec;
use crate::Value;
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Location {
pub line: u32,
pub column: u32,
}
impl Location {
#[must_use]
pub const fn new(line: u32, column: u32) -> Self {
Self { line, column }
}
}
impl fmt::Display for Location {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}:{}", self.line, self.column)
}
}
pub(crate) type Path = SmallVec<[PathSegment; 8]>;
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub enum PathSegment {
Field(Arc<str>),
Index(usize),
}
impl PathSegment {
#[must_use]
pub fn field(name: impl Into<Arc<str>>) -> Self {
Self::Field(name.into())
}
#[must_use]
pub const fn index(index: usize) -> Self {
Self::Index(index)
}
}
impl fmt::Display for PathSegment {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Field(name) => f.write_str(name),
Self::Index(index) => write!(f, "{index}"),
}
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct GraphQLError {
inner: Box<GraphQLErrorInner>,
}
#[derive(Clone, Debug, PartialEq)]
struct GraphQLErrorInner {
message: Cow<'static, str>,
locations: SmallVec<[Location; 1]>,
path: Option<Vec<PathSegment>>,
extensions: Option<crate::Object>,
}
impl GraphQLError {
#[must_use]
pub fn new(message: impl Into<Cow<'static, str>>) -> Self {
Self {
inner: Box::new(GraphQLErrorInner {
message: message.into(),
locations: SmallVec::new(),
path: None,
extensions: None,
}),
}
}
#[must_use]
pub fn at(mut self, location: Location) -> Self {
self.inner.locations.push(location);
self
}
#[must_use]
pub fn with_path(mut self, path: Vec<PathSegment>) -> Self {
self.inner.path = Some(path);
self
}
pub fn set_path(&mut self, path: Vec<PathSegment>) {
self.inner.path = Some(path);
}
pub fn path_mut(&mut self) -> Option<&mut Vec<PathSegment>> {
self.inner.path.as_mut()
}
#[must_use]
pub fn extend(mut self, key: impl Into<Arc<str>>, value: impl Into<Value>) -> Self {
self.inner
.extensions
.get_or_insert_with(crate::Object::new)
.insert(key, value.into());
self
}
#[must_use]
pub fn message(&self) -> &str {
&self.inner.message
}
#[must_use]
pub fn locations(&self) -> &[Location] {
&self.inner.locations
}
#[must_use]
pub fn path(&self) -> Option<&[PathSegment]> {
self.inner.path.as_deref()
}
#[must_use]
pub fn extensions(&self) -> Option<&crate::Object> {
self.inner.extensions.as_ref()
}
#[must_use]
pub fn with_message(mut self, message: impl Into<Cow<'static, str>>) -> Self {
self.inner.message = message.into();
self
}
}
impl fmt::Display for GraphQLError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.inner.message)?;
for location in &self.inner.locations {
write!(f, " (at {location})")?;
}
if let Some(path) = &self.inner.path {
f.write_str(" at path ")?;
for (index, segment) in path.iter().enumerate() {
if index != 0 {
f.write_str(".")?;
}
write!(f, "{segment}")?;
}
}
Ok(())
}
}
impl std::error::Error for GraphQLError {}
impl From<&str> for GraphQLError {
fn from(value: &str) -> Self {
Self::new(value.to_owned())
}
}
impl From<String> for GraphQLError {
fn from(value: String) -> Self {
Self::new(value)
}
}
impl From<Cow<'static, str>> for GraphQLError {
fn from(value: Cow<'static, str>) -> Self {
Self::new(value)
}
}
pub type Result<T, E = GraphQLError> = core::result::Result<T, E>;
#[cfg(feature = "serde")]
impl serde::Serialize for GraphQLError {
fn serialize<S: serde::Serializer>(
&self,
serializer: S,
) -> core::result::Result<S::Ok, S::Error> {
use serde::ser::SerializeMap as _;
let mut map = serializer.serialize_map(None)?;
map.serialize_entry("message", &self.inner.message)?;
if !self.inner.locations.is_empty() {
map.serialize_entry("locations", &self.inner.locations)?;
}
if let Some(path) = &self.inner.path {
map.serialize_entry("path", &PathRef(path))?;
}
if let Some(extensions) = &self.inner.extensions {
map.serialize_entry("extensions", extensions)?;
}
map.end()
}
}
#[cfg(feature = "serde")]
impl serde::Serialize for Location {
fn serialize<S: serde::Serializer>(
&self,
serializer: S,
) -> core::result::Result<S::Ok, S::Error> {
use serde::ser::SerializeMap as _;
let mut map = serializer.serialize_map(Some(2))?;
map.serialize_entry("line", &self.line)?;
map.serialize_entry("column", &self.column)?;
map.end()
}
}
#[cfg(feature = "serde")]
struct PathRef<'a>(&'a [PathSegment]);
#[cfg(feature = "serde")]
impl serde::Serialize for PathRef<'_> {
fn serialize<S: serde::Serializer>(
&self,
serializer: S,
) -> core::result::Result<S::Ok, S::Error> {
use serde::ser::SerializeSeq as _;
let mut seq = serializer.serialize_seq(Some(self.0.len()))?;
for segment in self.0 {
match segment {
PathSegment::Field(name) => seq.serialize_element(&**name)?,
PathSegment::Index(index) => seq.serialize_element(index)?,
}
}
seq.end()
}
}
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Response {
pub data: Option<Value>,
pub errors: Vec<GraphQLError>,
pub extensions: Option<crate::Object>,
}
impl Response {
#[must_use]
pub fn error(error: GraphQLError) -> Self {
Self {
data: None,
errors: vec![error],
extensions: None,
}
}
#[must_use]
pub fn data(data: Value) -> Self {
Self {
data: Some(data),
errors: Vec::new(),
extensions: None,
}
}
#[must_use]
pub fn has_errors(&self) -> bool {
!self.errors.is_empty()
}
}
#[cfg(feature = "serde")]
impl serde::Serialize for Response {
fn serialize<S: serde::Serializer>(
&self,
serializer: S,
) -> core::result::Result<S::Ok, S::Error> {
use serde::ser::SerializeMap as _;
let len = usize::from(self.data.is_some())
+ usize::from(!self.errors.is_empty())
+ usize::from(self.extensions.is_some());
let mut map = serializer.serialize_map(Some(len))?;
if let Some(data) = &self.data {
map.serialize_entry("data", data)?;
}
if !self.errors.is_empty() {
map.serialize_entry("errors", &self.errors)?;
}
if let Some(extensions) = &self.extensions {
map.serialize_entry("extensions", extensions)?;
}
map.end()
}
}