use anyhow::bail;
use serde::{Deserialize, Serialize};
use tokio_postgres::Row;
#[derive(Serialize, Deserialize, Debug)]
pub struct Currency {
pub id: CurrencyId,
pub name: String,
}
impl TryFrom<&Row> for Currency {
type Error = crate::Error;
fn try_from(value: &Row) -> Result<Self, Self::Error> {
let id: i64 = value.try_get("id")?;
let name: String = value.try_get("name")?;
Ok(Currency {
id: id.try_into()?,
name: name,
})
}
}
#[derive(Serialize, Deserialize, Debug)]
pub enum CurrencyId {
USD = 1,
None = 2,
}
impl TryFrom<i64> for CurrencyId {
type Error = anyhow::Error;
fn try_from(value: i64) -> Result<Self, Self::Error> {
let id = match value {
1 => CurrencyId::USD,
2 => CurrencyId::None,
_ => bail!("couldn't match value {value} to currency id"),
};
Ok(id)
}
}
impl TryFrom<&str> for CurrencyId {
type Error = anyhow::Error;
fn try_from(value: &str) -> Result<Self, Self::Error> {
let id = match value {
"USD" => CurrencyId::USD,
"" => CurrencyId::None,
_ => bail!("couldn't match value {value} to currency id"),
};
Ok(id)
}
}
impl From<&CurrencyId> for &str {
fn from(value: &CurrencyId) -> Self {
match value {
CurrencyId::USD => "USD",
CurrencyId::None => "",
}
}
}
impl From<&CurrencyId> for i64 {
fn from(value: &CurrencyId) -> Self {
match value {
CurrencyId::USD => 1,
CurrencyId::None => 2,
}
}
}
impl ToString for CurrencyId {
fn to_string(&self) -> String {
let s: &str = self.into();
s.to_string()
}
}