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