async-graphql/src/base.rs

67 lines
1.6 KiB
Rust
Raw Normal View History

2020-03-03 11:15:18 +00:00
use crate::{registry, ContextSelectionSet, Result};
2020-03-01 10:54:34 +00:00
use graphql_parser::query::Value;
2020-03-02 00:24:49 +00:00
use std::borrow::Cow;
2020-03-01 10:54:34 +00:00
2020-03-03 03:48:00 +00:00
#[doc(hidden)]
pub trait GQLType {
fn type_name() -> Cow<'static, str>;
2020-03-03 11:15:18 +00:00
fn qualified_type_name() -> String {
format!("{}!", Self::type_name())
}
fn create_type_info(registry: &mut registry::Registry) -> String;
2020-03-03 03:48:00 +00:00
}
#[doc(hidden)]
pub trait GQLInputValue: GQLType + Sized {
2020-03-04 02:38:07 +00:00
fn parse(value: &Value) -> Option<Self>;
2020-03-03 03:48:00 +00:00
}
#[doc(hidden)]
#[async_trait::async_trait]
pub trait GQLOutputValue: GQLType {
async fn resolve(&self, ctx: &ContextSelectionSet<'_>) -> Result<serde_json::Value>;
}
#[doc(hidden)]
pub trait GQLObject: GQLOutputValue {}
#[doc(hidden)]
pub trait GQLInputObject: GQLInputValue {}
2020-03-05 06:23:55 +00:00
pub trait GQLScalar: Sized + Send {
2020-03-01 10:54:34 +00:00
fn type_name() -> &'static str;
2020-03-03 11:15:18 +00:00
fn description() -> Option<&'static str> {
None
}
2020-03-04 02:38:07 +00:00
fn parse(value: &Value) -> Option<Self>;
2020-03-02 00:24:49 +00:00
fn to_json(&self) -> Result<serde_json::Value>;
2020-03-01 10:54:34 +00:00
}
2020-03-05 06:23:55 +00:00
impl<T: GQLScalar> GQLType for T {
2020-03-02 00:24:49 +00:00
fn type_name() -> Cow<'static, str> {
Cow::Borrowed(T::type_name())
2020-03-01 10:54:34 +00:00
}
2020-03-03 03:48:00 +00:00
2020-03-03 11:15:18 +00:00
fn create_type_info(registry: &mut registry::Registry) -> String {
registry.create_type::<T, _>(|_| registry::Type::Scalar {
2020-03-03 11:15:18 +00:00
name: T::type_name().to_string(),
description: T::description(),
})
2020-03-03 03:48:00 +00:00
}
2020-03-01 10:54:34 +00:00
}
2020-03-05 06:23:55 +00:00
impl<T: GQLScalar> GQLInputValue for T {
2020-03-04 02:38:07 +00:00
fn parse(value: &Value) -> Option<Self> {
2020-03-01 10:54:34 +00:00
T::parse(value)
}
}
#[async_trait::async_trait]
2020-03-05 06:23:55 +00:00
impl<T: GQLScalar + Sync> GQLOutputValue for T {
2020-03-02 00:24:49 +00:00
async fn resolve(&self, _: &ContextSelectionSet<'_>) -> Result<serde_json::Value> {
T::to_json(self)
2020-03-01 10:54:34 +00:00
}
}