async-graphql/src/scalars/string.rs

63 lines
1.7 KiB
Rust
Raw Normal View History

use crate::parser::Pos;
use crate::{
registry, ContextSelectionSet, InputValueError, InputValueResult, OutputValueType, Result,
ScalarType, Type, Value,
};
use async_graphql_derive::Scalar;
2020-03-02 00:24:49 +00:00
use std::borrow::Cow;
2020-03-21 01:32:13 +00:00
const STRING_DESC: &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-03 11:15:18 +00:00
#[Scalar(internal)]
impl ScalarType 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
}
fn parse(value: &Value) -> InputValueResult<Self> {
2020-03-02 00:24:49 +00:00
match value {
Value::String(s) => Ok(s.clone()),
_ => Err(InputValueError::ExpectedType),
2020-03-02 00:24:49 +00:00
}
}
2020-03-08 12:35:36 +00:00
fn is_valid(value: &Value) -> bool {
match value {
Value::String(_) => true,
_ => false,
}
}
2020-03-25 03:39:28 +00:00
fn to_json(&self) -> Result<serde_json::Value> {
Ok(self.clone().into())
2020-03-02 00:24:49 +00:00
}
}
2020-03-19 09:20:12 +00:00
impl<'a> Type for &'a str {
2020-03-02 00:24:49 +00:00
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-08 12:35:36 +00:00
is_valid: |value| match value {
Value::String(_) => true,
_ => false,
},
2020-03-03 11:15:18 +00:00
})
2020-03-03 03:48:00 +00:00
}
2020-03-02 00:24:49 +00:00
}
#[async_trait::async_trait]
2020-03-19 09:20:12 +00:00
impl<'a> OutputValueType for &'a str {
async fn resolve(&self, _: &ContextSelectionSet<'_>, _pos: Pos) -> Result<serde_json::Value> {
Ok((*self).into())
2020-03-02 00:24:49 +00:00
}
}