#[graphql_scalar]
Expand description
#[graphql_scalar]
macro.is interchangeable with
#[derive(
GraphQLScalar
)]
macro, and is used for deriving a
GraphQL scalar implementation.
/// Doc comments are used for the GraphQL type description.
#[graphql_scalar]
#[graphql(
// Custom GraphQL name.
name = "MyUserId",
// Description can also specified in the attribute.
// This will the doc comment, if one exists.
description = "...",
// Optional specification URL.
specified_by_url = "https://tools.ietf.org/html/rfc4122",
// Explicit generic scalar.
scalar = S: juniper::ScalarValue,
transparent,
)]
struct UserId(String);
ยงForeign types
Additionally, #[graphql_scalar]
can be used directly on foreign types via
type alias, without using the newtype pattern.
NOTE: To satisfy orphan rules you should provide local
ScalarValue
implementation.
use juniper::{graphql_scalar, InputValue, ScalarValue, Value};
#[graphql_scalar]
#[graphql(
with = date_scalar,
parse_token(String),
scalar = CustomScalarValue,
)]
// ^^^^^^^^^^^^^^^^^ local `ScalarValue` implementation
type Date = date::Date;
// ^^^^^^^^^^ type from another crate
mod date_scalar {
use super::*;
pub(super) fn to_output(v: &Date) -> Value<CustomScalarValue> {
Value::scalar(v.to_string())
}
pub(super) fn from_input(v: &InputValue<CustomScalarValue>) -> Result<Date, String> {
v.as_string_value()
.ok_or_else(|| format!("Expected `String`, found: {v}"))
.and_then(|s| s.parse().map_err(|e| format!("Failed to parse `Date`: {e}")))
}
}