Skip to content

Commit

Permalink
Fix schemas for bigdecimal/rust_decimal (#248)
Browse files Browse the repository at this point in the history
Both of these crates serialise decimals as strings, not as plain numbers
  • Loading branch information
GREsau authored Sep 17, 2023
1 parent a5e51b2 commit db1dd47
Show file tree
Hide file tree
Showing 5 changed files with 34 additions and 5 deletions.
4 changes: 4 additions & 0 deletions schemars/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -120,5 +120,9 @@ required-features = ["smol_str"]
name = "semver"
required-features = ["semver"]

[[test]]
name = "decimal"
required-features = ["rust_decimal", "bigdecimal"]

[package.metadata.docs.rs]
all-features = true
11 changes: 6 additions & 5 deletions schemars/src/json_schema_impls/decimal.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,19 +4,20 @@ use crate::JsonSchema;

macro_rules! decimal_impl {
($type:ty) => {
decimal_impl!($type => Number, "Number");
};
($type:ty => $instance_type:ident, $name:expr) => {
impl JsonSchema for $type {
no_ref_schema!();

fn schema_name() -> String {
$name.to_owned()
"Decimal".to_owned()
}

fn json_schema(_: &mut SchemaGenerator) -> Schema {
SchemaObject {
instance_type: Some(InstanceType::$instance_type.into()),
instance_type: Some(InstanceType::String.into()),
string: Some(Box::new(StringValidation {
pattern: Some(r"^-?[0-9]+(\.[0-9]+)?$".to_owned()),
..Default::default()
})),
..Default::default()
}
.into()
Expand Down
12 changes: 12 additions & 0 deletions schemars/tests/decimal.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
mod util;
use util::*;

#[test]
fn rust_decimal() -> TestResult {
test_default_generated_schema::<rust_decimal::Decimal>("rust_decimal")
}

#[test]
fn bigdecimal() -> TestResult {
test_default_generated_schema::<bigdecimal::BigDecimal>("bigdecimal")
}
6 changes: 6 additions & 0 deletions schemars/tests/expected/bigdecimal.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "Decimal",
"type": "string",
"pattern": "^-?[0-9]+(\\.[0-9]+)?$"
}
6 changes: 6 additions & 0 deletions schemars/tests/expected/rust_decimal.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "Decimal",
"type": "string",
"pattern": "^-?[0-9]+(\\.[0-9]+)?$"
}

0 comments on commit db1dd47

Please sign in to comment.