Implement JsonSchema on Url

This commit is contained in:
Alastair Feille 2020-11-30 18:54:09 -06:00 committed by Graham Esau
parent 3a2b425998
commit f0836d4415
6 changed files with 66 additions and 0 deletions

View file

@ -274,3 +274,4 @@ Schemars can implement `JsonSchema` on types from several popular crates, enable
- [`uuid`](https://crates.io/crates/uuid) (^0.8)
- [`smallvec`](https://crates.io/crates/smallvec) (^1.0)
- [`arrayvec`](https://crates.io/crates/arrayvec) (^0.5)
- [`url`](https://crates.io/crates/url) (^2.0)

View file

@ -24,6 +24,7 @@ either = { version = "1.3", default-features = false, optional = true }
uuid = { version = "0.8", default-features = false, optional = true }
smallvec = { version = "1.0", optional = true }
arrayvec = { version = "0.5", default-features = false, optional = true }
url = { version = "2.0", default-features = false, optional = true }
[dev-dependencies]
pretty_assertions = "0.6.1"
@ -77,5 +78,9 @@ required-features = ["impl_json_schema"]
name = "ui"
required-features = ["ui_test"]
[[test]]
name = "url"
required-features = ["url"]
[package.metadata.docs.rs]
all-features = true

View file

@ -64,6 +64,8 @@ mod serdejson;
mod smallvec;
mod time;
mod tuple;
#[cfg(feature = "url")]
mod url;
#[cfg(feature = "uuid")]
mod uuid;
mod wrapper;

View file

@ -0,0 +1,30 @@
use crate::gen::SchemaGenerator;
use crate::schema::*;
use crate::JsonSchema;
use url::Url;
macro_rules! formatted_string_impl {
($ty:ident, $format:literal) => {
formatted_string_impl!($ty, $format, JsonSchema for $ty);
};
($ty:ident, $format:literal, $($desc:tt)+) => {
impl $($desc)+ {
no_ref_schema!();
fn schema_name() -> String {
stringify!($ty).to_owned()
}
fn json_schema(_: &mut SchemaGenerator) -> Schema {
SchemaObject {
instance_type: Some(InstanceType::String.into()),
format: Some($format.to_owned()),
..Default::default()
}
.into()
}
}
};
}
formatted_string_impl!(Url, "uri");

View file

@ -0,0 +1,14 @@
{
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "UrlTypes",
"type": "object",
"required": [
"url"
],
"properties": {
"url": {
"type": "string",
"format": "uri"
}
}
}

14
schemars/tests/url.rs Normal file
View file

@ -0,0 +1,14 @@
mod util;
use schemars::JsonSchema;
use url::Url;
use util::*;
#[derive(Debug, JsonSchema)]
struct UrlTypes {
url: Url,
}
#[test]
fn url_types() -> TestResult {
test_default_generated_schema::<UrlTypes>("url")
}