2020-05-10 10:27:46 +00:00
|
|
|
use crate::{InputValueError, InputValueResult, Result, ScalarType, Value};
|
2020-05-05 05:21:45 +00:00
|
|
|
use async_graphql_derive::Scalar;
|
|
|
|
use std::ops::{Deref, DerefMut};
|
|
|
|
|
|
|
|
/// Cursor scalar
|
|
|
|
///
|
|
|
|
/// A custom scalar that serializes as a string.
|
|
|
|
/// https://relay.dev/graphql/connections.htm#sec-Cursor
|
|
|
|
#[derive(Clone, Ord, PartialOrd, Eq, PartialEq, Hash, Debug)]
|
|
|
|
pub struct Cursor(String);
|
|
|
|
|
|
|
|
impl std::fmt::Display for Cursor {
|
|
|
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
|
|
|
write!(f, "{}", self.0)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Deref for Cursor {
|
|
|
|
type Target = String;
|
|
|
|
|
|
|
|
fn deref(&self) -> &Self::Target {
|
|
|
|
&self.0
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl DerefMut for Cursor {
|
|
|
|
fn deref_mut(&mut self) -> &mut Self::Target {
|
|
|
|
&mut self.0
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl From<String> for Cursor {
|
|
|
|
fn from(value: String) -> Self {
|
|
|
|
Cursor(value)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<'a> From<&'a str> for Cursor {
|
|
|
|
fn from(value: &'a str) -> Self {
|
|
|
|
Cursor(value.to_string())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl From<usize> for Cursor {
|
|
|
|
fn from(value: usize) -> Self {
|
|
|
|
Cursor(value.to_string())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-05-10 10:38:20 +00:00
|
|
|
/// Convert any type that implements Display to the Cursor type
|
|
|
|
pub trait ToGraphQLCursor {
|
|
|
|
#[allow(missing_docs)]
|
|
|
|
fn to_graphql_cursor(&self) -> Cursor;
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<T> ToGraphQLCursor for T
|
|
|
|
where
|
|
|
|
T: std::fmt::Display,
|
|
|
|
{
|
|
|
|
fn to_graphql_cursor(&self) -> Cursor {
|
|
|
|
Cursor(self.to_string())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-05-05 05:21:45 +00:00
|
|
|
#[Scalar(internal)]
|
|
|
|
impl ScalarType for Cursor {
|
|
|
|
fn type_name() -> &'static str {
|
|
|
|
"Cursor"
|
|
|
|
}
|
|
|
|
|
2020-05-10 10:27:46 +00:00
|
|
|
fn parse(value: &Value) -> InputValueResult<Self> {
|
2020-05-05 05:21:45 +00:00
|
|
|
match value {
|
2020-05-10 10:27:46 +00:00
|
|
|
Value::String(s) => Ok(Cursor(s.into())),
|
|
|
|
_ => Err(InputValueError::ExpectedType),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn is_valid(value: &Value) -> bool {
|
|
|
|
match value {
|
|
|
|
Value::String(_) => true,
|
|
|
|
_ => false,
|
2020-05-05 05:21:45 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn to_json(&self) -> Result<serde_json::Value> {
|
|
|
|
Ok(self.0.to_string().into())
|
|
|
|
}
|
|
|
|
}
|