async-graphql/src/validation/rules/variables_are_input_types.rs

66 lines
1.5 KiB
Rust
Raw Normal View History

2022-04-19 04:25:11 +00:00
use crate::{
parser::types::VariableDefinition,
validation::visitor::{Visitor, VisitorContext},
Positioned,
};
2020-03-10 06:14:09 +00:00
#[derive(Default)]
pub struct VariablesAreInputTypes;
impl<'a> Visitor<'a> for VariablesAreInputTypes {
fn enter_variable_definition(
&mut self,
2020-03-22 08:45:59 +00:00
ctx: &mut VisitorContext<'a>,
2020-05-10 02:59:51 +00:00
variable_definition: &'a Positioned<VariableDefinition>,
2020-03-10 06:14:09 +00:00
) {
if let Some(ty) = ctx
.registry
2020-09-06 05:38:31 +00:00
.concrete_type_by_parsed_type(&variable_definition.node.var_type.node)
2020-03-10 06:14:09 +00:00
{
if !ty.is_input() {
ctx.report_error(
2020-09-06 05:38:31 +00:00
vec![variable_definition.pos],
2020-03-10 06:14:09 +00:00
format!(
"Variable \"{}\" cannot be of non-input type \"{}\"",
2020-09-06 05:38:31 +00:00
variable_definition.node.name.node,
2020-03-10 06:14:09 +00:00
ty.name()
),
);
}
}
}
}
2020-04-05 08:00:26 +00:00
#[cfg(test)]
mod tests {
use super::*;
pub fn factory() -> VariablesAreInputTypes {
VariablesAreInputTypes
}
#[test]
fn input_types_are_valid() {
2020-05-29 09:29:15 +00:00
expect_passes_rule!(
2020-04-05 08:00:26 +00:00
factory,
r#"
query Foo($a: String, $b: [Boolean!]!, $c: ComplexInput) {
field(a: $a, b: $b, c: $c)
}
"#,
);
}
#[test]
fn output_types_are_invalid() {
2020-05-29 09:29:15 +00:00
expect_fails_rule!(
2020-04-05 08:00:26 +00:00
factory,
r#"
query Foo($a: Dog, $b: [[CatOrDog!]]!, $c: Pet) {
field(a: $a, b: $b, c: $c)
}
"#,
);
}
}