this repo has no description
1use crate::api::error::ApiError;
2use crate::validation::{RecordValidator, ValidationError, ValidationStatus};
3use axum::response::Response;
4
5pub fn validate_record(record: &serde_json::Value, collection: &str) -> Result<(), Box<Response>> {
6 validate_record_with_rkey(record, collection, None)
7}
8
9pub fn validate_record_with_rkey(
10 record: &serde_json::Value,
11 collection: &str,
12 rkey: Option<&str>,
13) -> Result<(), Box<Response>> {
14 let validator = RecordValidator::new();
15 validation_error_to_response(validator.validate_with_rkey(record, collection, rkey))
16}
17
18pub fn validate_record_with_status(
19 record: &serde_json::Value,
20 collection: &str,
21 rkey: Option<&str>,
22 require_lexicon: bool,
23) -> Result<ValidationStatus, Box<Response>> {
24 let validator = RecordValidator::new().require_lexicon(require_lexicon);
25 match validator.validate_with_rkey(record, collection, rkey) {
26 Ok(status) => Ok(status),
27 Err(e) => Err(validation_error_to_box_response(e)),
28 }
29}
30
31fn validation_error_to_response(
32 result: Result<ValidationStatus, ValidationError>,
33) -> Result<(), Box<Response>> {
34 match result {
35 Ok(_) => Ok(()),
36 Err(e) => Err(validation_error_to_box_response(e)),
37 }
38}
39
40fn validation_error_to_box_response(e: ValidationError) -> Box<Response> {
41 use axum::response::IntoResponse;
42 let msg = match e {
43 ValidationError::MissingType => "Record must have a $type field".to_string(),
44 ValidationError::TypeMismatch { expected, actual } => {
45 format!(
46 "Record $type '{}' does not match collection '{}'",
47 actual, expected
48 )
49 }
50 ValidationError::MissingField(field) => format!("Missing required field: {}", field),
51 ValidationError::InvalidField { path, message } => {
52 format!("Invalid field '{}': {}", path, message)
53 }
54 ValidationError::InvalidDatetime { path } => {
55 format!("Invalid datetime format at '{}'", path)
56 }
57 ValidationError::BannedContent { path } => {
58 format!("Unacceptable slur in record at '{}'", path)
59 }
60 ValidationError::UnknownType(type_name) => format!("Lexicon not found: lex:{}", type_name),
61 e => e.to_string(),
62 };
63 Box::new(ApiError::InvalidRecord(msg).into_response())
64}