async-graphql/src/types/connection/cursor.rs

57 lines
1.1 KiB
Rust
Raw Normal View History

use std::convert::Infallible;
use std::fmt::Display;
2020-09-10 01:09:55 +00:00
use std::num::ParseIntError;
2020-10-15 06:38:10 +00:00
use crate::ID;
/// Cursor type
///
/// A custom scalar that serializes as a string.
/// https://relay.dev/graphql/connections.htm#sec-Cursor
pub trait CursorType: Sized {
/// Error type for `decode_cursor`.
type Error: Display;
/// Decode cursor from string.
fn decode_cursor(s: &str) -> Result<Self, Self::Error>;
/// Encode cursor to string.
fn encode_cursor(&self) -> String;
}
impl CursorType for usize {
type Error = ParseIntError;
fn decode_cursor(s: &str) -> Result<Self, Self::Error> {
s.parse()
}
fn encode_cursor(&self) -> String {
self.to_string()
}
}
impl CursorType for String {
type Error = Infallible;
fn decode_cursor(s: &str) -> Result<Self, Self::Error> {
Ok(s.to_string())
2020-05-10 14:25:16 +00:00
}
fn encode_cursor(&self) -> String {
self.clone()
}
}
impl CursorType for ID {
type Error = Infallible;
fn decode_cursor(s: &str) -> Result<Self, Self::Error> {
Ok(s.to_string().into())
}
fn encode_cursor(&self) -> String {
self.to_string()
}
}