Skip to content

Commit

Permalink
Parse Value(Number) into Decimal (#452)
Browse files Browse the repository at this point in the history
* Parse Value(Number) into Decimal

* Allow parsing floats as well
  • Loading branch information
VersBinarii authored Dec 17, 2022
1 parent fb7cbe7 commit e8161d9
Showing 1 changed file with 12 additions and 4 deletions.
16 changes: 12 additions & 4 deletions poem-openapi/src/types/external/decimal.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,10 +41,18 @@ impl Type for Decimal {
impl ParseFromJSON for Decimal {
fn parse_from_json(value: Option<Value>) -> ParseResult<Self> {
let value = value.unwrap_or_default();
if let Value::String(value) = value {
Ok(value.parse()?)
} else {
Err(ParseError::expected_type(value))
match value {
Value::String(value) => Ok(value.parse()?),
Value::Number(num) if num.is_i64() => Ok(Decimal::from(
num.as_i64()
.ok_or_else(|| ParseError::custom("Expected a number"))?,
)),
Value::Number(num) if num.is_f64() => Ok(Decimal::from_f64_retain(
num.as_f64()
.ok_or_else(|| ParseError::custom("Expected a float"))?,
)
.ok_or_else(|| ParseError::custom("Error converting to decimal"))?),
_ => Err(ParseError::expected_type(value)),
}
}
}
Expand Down

0 comments on commit e8161d9

Please sign in to comment.