2020-03-08 12:35:36 +00:00
|
|
|
use crate::error::RuleError;
|
|
|
|
use crate::registry::{Registry, Type};
|
2020-03-09 04:08:50 +00:00
|
|
|
use graphql_parser::query::{Definition, Document};
|
2020-03-08 12:35:36 +00:00
|
|
|
use graphql_parser::Pos;
|
2020-03-09 04:08:50 +00:00
|
|
|
use std::collections::HashSet;
|
2020-03-08 12:35:36 +00:00
|
|
|
|
|
|
|
pub struct ValidatorContext<'a> {
|
|
|
|
pub registry: &'a Registry,
|
|
|
|
pub errors: Vec<RuleError>,
|
|
|
|
type_stack: Vec<&'a Type>,
|
2020-03-09 04:08:50 +00:00
|
|
|
fragments_names: HashSet<&'a str>,
|
2020-03-08 12:35:36 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
impl<'a> ValidatorContext<'a> {
|
2020-03-09 04:08:50 +00:00
|
|
|
pub fn new(registry: &'a Registry, doc: &'a Document) -> Self {
|
2020-03-08 12:35:36 +00:00
|
|
|
Self {
|
|
|
|
registry,
|
|
|
|
errors: Default::default(),
|
|
|
|
type_stack: Default::default(),
|
2020-03-09 04:08:50 +00:00
|
|
|
fragments_names: doc
|
|
|
|
.definitions
|
|
|
|
.iter()
|
|
|
|
.filter_map(|d| match d {
|
|
|
|
Definition::Fragment(fragment) => Some(fragment.name.as_str()),
|
|
|
|
_ => None,
|
|
|
|
})
|
|
|
|
.collect(),
|
2020-03-08 12:35:36 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn report_error<T: Into<String>>(&mut self, locations: Vec<Pos>, msg: T) {
|
|
|
|
self.errors.push(RuleError {
|
|
|
|
locations,
|
|
|
|
message: msg.into(),
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2020-03-09 04:08:50 +00:00
|
|
|
pub fn append_errors(&mut self, errors: Vec<RuleError>) {
|
|
|
|
self.errors.extend(errors);
|
|
|
|
}
|
|
|
|
|
2020-03-08 12:35:36 +00:00
|
|
|
pub fn with_type<F: FnMut(&mut ValidatorContext<'a>)>(&mut self, ty: &'a Type, mut f: F) {
|
|
|
|
self.type_stack.push(ty);
|
|
|
|
f(self);
|
|
|
|
self.type_stack.pop();
|
|
|
|
}
|
|
|
|
|
2020-03-09 04:08:50 +00:00
|
|
|
pub fn parent_type(&self) -> Option<&'a Type> {
|
|
|
|
self.type_stack.get(self.type_stack.len() - 2).map(|t| *t)
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn current_type(&self) -> &'a Type {
|
2020-03-08 12:35:36 +00:00
|
|
|
self.type_stack.last().unwrap()
|
|
|
|
}
|
2020-03-09 04:08:50 +00:00
|
|
|
|
|
|
|
pub fn is_known_fragment(&self, name: &str) -> bool {
|
|
|
|
self.fragments_names.contains(name)
|
|
|
|
}
|
2020-03-08 12:35:36 +00:00
|
|
|
}
|