schemars
schemars copied to clipboard
Add example for total manual implemenation of `JsonSchema`
trafficstars
I was looking for an example of a totally manual implementation of JsonSchema but could not find this easily so created one by combining a few different things.
Note that there does exists an example that might fit for easier cases: https://github.com/GREsau/schemars/blob/master/schemars/examples/custom_serialization.rs
This did not cover in my case, so needed to implement the trait manually.
Here is my code (don't have time to create PR right now):
#[derive(Clone, Copy, Debug)]
pub struct Permission {
pub read: bool,
pub write: bool,
pub delete: bool,
}
/// Manual implementation of JsonSchema because it need to be similar to `String`.
impl JsonSchema for Permission {
fn schema_name() -> String {
"Permission".to_owned()
}
fn json_schema(_: &mut SchemaGenerator) -> Schema {
SchemaObject {
instance_type: Some(InstanceType::String.into()),
format: None,
string: Some(Box::new(StringValidation {
max_length: Some(3),
min_length: None,
// Regex for permissions
pattern: Some("^r?w?d?$".to_owned()),
})),
metadata: Some(Box::new(Metadata {
description: Some(
"Permissions given to a specific object or user.<br/>
This string can contain the following permissions:<br/>
- Read (`r`): Entity has read permissions,<br/>
- Write (`w`): Entity has change/upload/add permissions,<br/>
- Delete (`d`): Entity has permission to delete items,<br/>
The letters that are present in the string are the given permissions.<br/>
<br/>
Example: \"rw\" is equal to read and write permissions.<br/>
But delete permissions are not granted."
.to_owned(),
),
examples: vec![json!("rw"), json!("rwd"), json!("r"), json!("")],
..Default::default()
})),
..Default::default()
}
.into()
}
fn is_referenceable() -> bool {
false
}
}
impl Serialize for Permission {
// ...
}
impl<'de> Deserialize<'de> for Permission {
// ...
}
Hope this helps some people out. Might be a good idea to add this example to this page: https://docs.rs/schemars/0.8.7/schemars/trait.JsonSchema.html Or a link to it, also the other example would be nice.