use ash_jsonschema::validator::CompileError;
use ash_jsonschema::validator::Mode;
use ash_jsonschema::{Schema, SchemaError, Validator};
use crate::context::Context;
use crate::error::JsonApiError;
use crate::serialize::{RelationshipDef, Schema as ResourceDef};
#[derive(Debug)]
pub enum BuildError {
Schema(SchemaError),
Attributes(serde_json::Error),
Compile(CompileError),
}
impl std::fmt::Display for BuildError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Schema(err) => write!(f, "derived schema is invalid: {err}"),
Self::Attributes(err) => write!(f, "attribute schema did not parse: {err}"),
Self::Compile(err) => write!(f, "schema did not compile: {err}"),
}
}
}
impl std::error::Error for BuildError {}
impl From<SchemaError> for BuildError {
fn from(err: SchemaError) -> Self {
Self::Schema(err)
}
}
impl From<serde_json::Error> for BuildError {
fn from(err: serde_json::Error) -> Self {
Self::Attributes(err)
}
}
impl From<CompileError> for BuildError {
fn from(err: CompileError) -> Self {
Self::Compile(err)
}
}
pub struct DocumentValidator {
validator: Validator,
}
type FormatCheck = Box<dyn Fn(&str) -> bool + Send + Sync>;
pub struct ValidatorBuilder<'a, S: ResourceDef> {
schema: &'a S,
attributes: serde_json::Value,
hidden: Vec<String>,
assert_formats: bool,
formats: Vec<(String, FormatCheck)>,
}
impl<'a, S: ResourceDef> ValidatorBuilder<'a, S> {
#[must_use]
pub fn attributes(mut self, schema: serde_json::Value) -> Self {
self.attributes = schema;
self
}
#[must_use]
pub fn hide(mut self, names: impl IntoIterator<Item = impl Into<String>>) -> Self {
self.hidden.extend(names.into_iter().map(Into::into));
self
}
#[must_use]
pub fn annotate_formats(mut self) -> Self {
self.assert_formats = false;
self
}
#[must_use]
pub fn format<F>(mut self, name: impl Into<String>, check: F) -> Self
where
F: Fn(&str) -> bool + Send + Sync + 'static,
{
self.formats.push((name.into(), Box::new(check)));
self
}
pub fn build(mut self) -> Result<DocumentValidator, BuildError> {
if let Some(properties) = self
.attributes
.get_mut("properties")
.and_then(|p| p.as_object_mut())
{
properties.retain(|name, _| !self.hidden.iter().any(|hidden| hidden == name));
}
let mut resource = Schema::object()
.required_property(
"type",
Schema::string().constant(self.schema.name().to_string()),
)
.required_property("attributes", Schema::from_value(self.attributes)?);
let relationships = self.schema.relationships();
if !relationships.is_empty() {
resource = resource.property("relationships", relationships_schema(relationships)?);
}
let document = Schema::object()
.required_property("data", resource.build()?)
.build()?;
let mut validator = Validator::builder(&document);
if self.assert_formats {
validator = validator.assert_formats();
}
for (name, check) in self.formats {
validator = validator.format(name, move |value| check(value));
}
Ok(DocumentValidator {
validator: validator.build()?,
})
}
}
impl DocumentValidator {
pub fn builder<S: ResourceDef>(schema: &S) -> ValidatorBuilder<'_, S> {
ValidatorBuilder {
schema,
attributes: serde_json::json!({ "type": "object" }),
hidden: Vec::new(),
assert_formats: true,
formats: Vec::new(),
}
}
pub fn parse(&self, body: &str, ctx: &Context) -> Result<serde_json::Value, Vec<JsonApiError>> {
let json: serde_json::Value = serde_json::from_str(body).map_err(|err| {
vec![JsonApiError::invalid(
ctx,
format!("malformed JSON: {err}"),
"",
)]
})?;
self.check(&json, ctx)?;
Ok(json)
}
pub fn check(&self, body: &serde_json::Value, ctx: &Context) -> Result<(), Vec<JsonApiError>> {
let outcome = self.validator.validate(body, Mode::All);
if outcome.errors.is_empty() {
return Ok(());
}
Err(outcome
.errors
.iter()
.map(|error| {
JsonApiError::invalid(ctx, error.message(), error.instance_location.clone())
})
.collect())
}
}
fn relationships_schema<R: RelationshipDef>(defs: &[R]) -> Result<Schema, SchemaError> {
let mut relationships = Schema::object();
for rel in defs {
let identifier = Schema::object()
.required_property("type", Schema::string().constant(rel.target().to_string()))
.required_property("id", Schema::string().min_length(1))
.build()?;
let data = if rel.is_to_many() {
Schema::array().items(identifier).build()?
} else {
identifier
};
relationships = relationships.property(
rel.name().to_string(),
Schema::object().required_property("data", data).build()?,
);
}
relationships.build()
}