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

181 lines
5.4 KiB
Rust
Raw Normal View History

2020-03-21 01:32:13 +00:00
mod connection_type;
2020-03-19 09:20:12 +00:00
mod edge;
mod page_info;
mod slice;
use crate::{Context, FieldResult, ObjectType};
2020-03-19 09:20:12 +00:00
2020-03-21 01:32:13 +00:00
pub use connection_type::Connection;
2020-03-19 09:20:12 +00:00
2020-03-20 03:56:08 +00:00
/// Connection query operation
2020-03-19 09:20:12 +00:00
pub enum QueryOperation<'a> {
2020-03-20 03:56:08 +00:00
/// Forward query
2020-03-19 09:20:12 +00:00
Forward {
2020-03-20 03:56:08 +00:00
/// After this cursor
2020-03-19 09:20:12 +00:00
after: Option<&'a str>,
2020-03-20 03:56:08 +00:00
/// How many records did this query return
2020-03-19 09:20:12 +00:00
limit: usize,
},
2020-03-20 03:56:08 +00:00
/// Backward query
2020-03-19 09:20:12 +00:00
Backward {
2020-03-20 03:56:08 +00:00
/// Before this cursor
2020-03-19 09:20:12 +00:00
before: Option<&'a str>,
2020-03-20 03:56:08 +00:00
/// How many records did this query return
2020-03-19 09:20:12 +00:00
limit: usize,
},
}
2020-03-20 03:56:08 +00:00
/// Empty edge extension object
2020-04-17 03:06:33 +00:00
#[async_graphql_derive::SimpleObject(internal)]
2020-03-19 09:20:12 +00:00
pub struct EmptyEdgeFields;
2020-03-20 03:56:08 +00:00
/// Data source of GraphQL Cursor Connections type
2020-03-19 09:20:12 +00:00
///
/// `Edge` is an extension object type that extends the edge fields, If you don't need it, you can use `EmptyEdgeFields`.
///
/// # References
/// (GraphQL Cursor Connections Specification)[https://facebook.github.io/relay/graphql/connections.htm]
///
/// # Examples
///
/// ```rust
/// use async_graphql::*;
/// use byteorder::{ReadBytesExt, BE};
///
/// struct QueryRoot;
///
2020-04-17 03:06:33 +00:00
/// #[SimpleObject]
/// struct DiffFields {
/// diff: i32,
2020-03-19 09:20:12 +00:00
/// }
///
/// struct Numbers;
///
2020-04-17 03:06:33 +00:00
/// #[DataSource]
2020-03-19 09:20:12 +00:00
/// impl DataSource for Numbers {
/// type Element = i32;
2020-03-20 03:56:08 +00:00
/// type EdgeFieldsObj = DiffFields;
2020-03-19 09:20:12 +00:00
///
/// async fn query_operation(&self, operation: &QueryOperation<'_>) -> FieldResult<Connection<Self::Element, Self::EdgeFieldsObj>> {
2020-03-19 09:20:12 +00:00
/// let (start, end) = match operation {
/// QueryOperation::Forward {after, limit} => {
/// let start = after.and_then(|after| base64::decode(after).ok())
/// .and_then(|data| data.as_slice().read_i32::<BE>().ok())
/// .map(|idx| idx + 1)
/// .unwrap_or(0);
/// let end = start + *limit as i32;
/// (start, end)
/// }
/// QueryOperation::Backward {before, limit} => {
/// let end = before.and_then(|before| base64::decode(before).ok())
/// .and_then(|data| data.as_slice().read_i32::<BE>().ok())
/// .unwrap_or(0);
/// let start = end - *limit as i32;
/// (start, end)
/// }
/// };
///
2020-04-17 03:06:33 +00:00
/// let nodes = (start..end).into_iter().map(|n| (base64::encode(n.to_be_bytes()), DiffFields {diff: n - 1000}, n)).collect();
2020-03-19 09:20:12 +00:00
/// Ok(Connection::new(None, true, true, nodes))
/// }
/// }
///
/// #[Object]
/// impl QueryRoot {
/// async fn numbers(&self, ctx: &Context<'_>,
/// after: Option<String>,
/// before: Option<String>,
/// first: Option<i32>,
/// last: Option<i32>
/// ) -> FieldResult<Connection<i32, DiffFields>> {
2020-03-19 09:20:12 +00:00
/// Numbers.query(ctx, after, before, first, last).await
/// }
/// }
///
/// #[async_std::main]
/// async fn main() {
/// let schema = Schema::new(QueryRoot, EmptyMutation, EmptySubscription);
///
2020-04-02 04:53:53 +00:00
/// assert_eq!(schema.execute("{ numbers(first: 2) { edges { node } } }").await.unwrap().data, serde_json::json!({
2020-03-19 09:20:12 +00:00
/// "numbers": {
/// "edges": [
/// {"node": 0},
/// {"node": 1}
/// ]
/// },
/// }));
///
2020-04-02 04:53:53 +00:00
/// assert_eq!(schema.execute("{ numbers(last: 2) { edges { node diff } } }").await.unwrap().data, serde_json::json!({
2020-03-19 09:20:12 +00:00
/// "numbers": {
/// "edges": [
/// {"node": -2, "diff": -1002},
/// {"node": -1, "diff": -1001}
/// ]
/// },
/// }));
/// }
/// ```
#[async_trait::async_trait]
pub trait DataSource: Sync + Send {
2020-03-20 03:56:08 +00:00
/// Record type
2020-03-19 09:20:12 +00:00
type Element;
2020-03-20 03:56:08 +00:00
/// Fields for Edge
///
/// Is a type that implements `ObjectType` and can be defined by the procedure macro `#[Object]`.
type EdgeFieldsObj: ObjectType + Send + Sync;
/// Execute the query.
2020-03-19 09:20:12 +00:00
async fn query(
&self,
_ctx: &Context<'_>,
2020-03-19 09:20:12 +00:00
after: Option<String>,
before: Option<String>,
first: Option<i32>,
last: Option<i32>,
) -> FieldResult<Connection<Self::Element, Self::EdgeFieldsObj>> {
2020-03-19 09:20:12 +00:00
let operation = if let Some(after) = &after {
QueryOperation::Forward {
after: Some(after),
limit: match first {
Some(value) => value.max(0) as usize,
2020-03-19 09:20:12 +00:00
None => 10,
},
}
} else if let Some(before) = &before {
QueryOperation::Backward {
before: Some(before),
limit: match last {
Some(value) => value.max(0) as usize,
2020-03-19 09:20:12 +00:00
None => 10,
},
}
} else if let Some(first) = first {
QueryOperation::Forward {
after: None,
limit: first.max(0) as usize,
2020-03-19 09:20:12 +00:00
}
} else if let Some(last) = last {
QueryOperation::Backward {
before: None,
limit: last.max(0) as usize,
2020-03-19 09:20:12 +00:00
}
} else {
QueryOperation::Forward {
after: None,
limit: 10,
}
};
self.query_operation(&operation).await
}
2020-03-20 03:56:08 +00:00
/// Parses the parameters and executes the queryUsually you just need to implement this method.
2020-03-19 09:20:12 +00:00
async fn query_operation(
&self,
operation: &QueryOperation<'_>,
) -> FieldResult<Connection<Self::Element, Self::EdgeFieldsObj>>;
2020-03-19 09:20:12 +00:00
}