From 09172b2b5d849cc91ab84351e5909c4d1fc0e7af Mon Sep 17 00:00:00 2001 From: Thomas Eizinger Date: Tue, 19 Oct 2021 16:48:41 +1100 Subject: [PATCH] Make `OrderId` always represent as `Hyphenated` in DB --- daemon/src/model/cfd.rs | 40 ++++++++++++++++++++++++++++++++++++---- 1 file changed, 36 insertions(+), 4 deletions(-) diff --git a/daemon/src/model/cfd.rs b/daemon/src/model/cfd.rs index 5f6ecf0..ca10583 100644 --- a/daemon/src/model/cfd.rs +++ b/daemon/src/model/cfd.rs @@ -11,21 +11,44 @@ use rocket::request::FromParam; use rust_decimal::prelude::{FromPrimitive, ToPrimitive}; use rust_decimal::Decimal; use rust_decimal_macros::dec; +use serde::de::Error as _; use serde::{Deserialize, Serialize}; use std::collections::HashMap; use std::fmt; use std::ops::{Neg, RangeInclusive}; use std::time::SystemTime; use time::Duration; +use uuid::adapter::Hyphenated; use uuid::Uuid; -#[derive(Debug, Copy, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, sqlx::Type)] +#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, sqlx::Type)] #[sqlx(transparent)] -pub struct OrderId(Uuid); +pub struct OrderId(Hyphenated); + +impl Serialize for OrderId { + fn serialize(&self, serializer: S) -> Result + where + S: serde::Serializer, + { + serializer.serialize_str(&self.0.to_string()) + } +} + +impl<'de> Deserialize<'de> for OrderId { + fn deserialize(deserializer: D) -> Result + where + D: serde::Deserializer<'de>, + { + let uuid = String::deserialize(deserializer)?; + let uuid = uuid.parse::().map_err(D::Error::custom)?; + + Ok(Self(uuid.to_hyphenated())) + } +} impl Default for OrderId { fn default() -> Self { - Self(Uuid::new_v4()) + Self(Uuid::new_v4().to_hyphenated()) } } @@ -40,7 +63,7 @@ impl<'v> FromParam<'v> for OrderId { fn from_param(param: &'v str) -> Result { let uuid = param.parse::()?; - Ok(OrderId(uuid)) + Ok(OrderId(uuid.to_hyphenated())) } } @@ -1615,6 +1638,15 @@ mod tests { Decimal::ZERO ); } + + #[test] + fn order_id_serde_roundtrip() { + let id = OrderId::default(); + + let deserialized = serde_json::from_str(&serde_json::to_string(&id).unwrap()).unwrap(); + + assert_eq!(id, deserialized); + } } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]