async-graphql/src/scalars/string.rs

50 lines
1.3 KiB
Rust
Raw Normal View History

2020-03-06 15:58:43 +00:00
use crate::{
impl_scalar, registry, ContextSelectionSet, GQLOutputValue, GQLScalar, GQLType, Result, Value,
};
2020-03-02 00:24:49 +00:00
use std::borrow::Cow;
2020-03-03 11:15:18 +00:00
const STRING_DESC:&'static str = "The `String` scalar type represents textual data, represented as UTF-8 character sequences. The String type is most often used by GraphQL to represent free-form human-readable text.";
2020-03-05 06:23:55 +00:00
impl GQLScalar for String {
2020-03-02 00:24:49 +00:00
fn type_name() -> &'static str {
2020-03-03 11:15:18 +00:00
"String"
}
fn description() -> Option<&'static str> {
Some(STRING_DESC)
2020-03-02 00:24:49 +00:00
}
2020-03-04 02:38:07 +00:00
fn parse(value: &Value) -> Option<Self> {
2020-03-02 00:24:49 +00:00
match value {
2020-03-04 02:38:07 +00:00
Value::String(s) => Some(s.clone()),
2020-03-03 11:15:18 +00:00
_ => None,
2020-03-02 00:24:49 +00:00
}
}
fn to_json(&self) -> Result<serde_json::Value> {
Ok(self.clone().into())
}
}
2020-03-06 15:58:43 +00:00
impl_scalar!(String);
2020-03-02 00:24:49 +00:00
impl<'a> GQLType for &'a str {
fn type_name() -> Cow<'static, str> {
2020-03-03 11:15:18 +00:00
Cow::Borrowed("String")
2020-03-02 00:24:49 +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::<Self, _>(|_| registry::Type::Scalar {
2020-03-03 11:15:18 +00:00
name: Self::type_name().to_string(),
description: Some(STRING_DESC),
})
2020-03-03 03:48:00 +00:00
}
2020-03-02 00:24:49 +00:00
}
#[async_trait::async_trait]
impl<'a> GQLOutputValue for &'a str {
2020-03-06 15:58:43 +00:00
async fn resolve(value: &Self, _: &ContextSelectionSet<'_>) -> Result<serde_json::Value> {
Ok(value.to_string().into())
2020-03-02 00:24:49 +00:00
}
}