use schemars::{JsonSchema, Schema};
use serde::{Deserialize, Serialize};
use serde_json::json;
use super::FormatSpec;
use super::schema::add_rule;
#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
#[schemars(transform = one_rule)]
#[non_exhaustive]
pub struct EntryParams {
pub message: String,
#[serde(default)]
pub format: Option<FormatSpec>,
#[serde(default)]
#[schemars(range(min = 1))]
pub length: Option<usize>,
#[serde(default)]
#[schemars(range(min = 1))]
pub min_length: Option<usize>,
#[serde(default)]
#[schemars(range(min = 1))]
pub max_length: Option<usize>,
}
fn one_rule(schema: &mut Schema) {
let absent = |fields: &[&str]| -> Vec<serde_json::Value> {
fields
.iter()
.map(|field| json!({ "not": { "required": [field] } }))
.collect()
};
add_rule(
schema,
json!({
"if": { "required": ["length"] },
"then": {
"allOf": absent(&["min_length", "max_length"]),
"x-message": "'length' is exact, so 'min_length' and 'max_length' cannot be \
given beside it",
},
}),
);
add_rule(
schema,
json!({
"if": {
"properties": { "format": { "type": "object" } },
"required": ["format"],
},
"then": {
"allOf": absent(&["length", "min_length", "max_length"]),
"x-message": "a pattern says the whole shape of the value, so 'length', \
'min_length' and 'max_length' cannot be given beside it",
},
}),
);
}