forked from 2sys/phonograph
46 lines
1.5 KiB
Rust
46 lines
1.5 KiB
Rust
|
|
use chrono::{DateTime, Utc};
|
||
|
|
use serde::{Deserialize, Serialize};
|
||
|
|
use sqlx::Postgres;
|
||
|
|
use uuid::Uuid;
|
||
|
|
|
||
|
|
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
|
||
|
|
#[serde(tag = "t", content = "c")]
|
||
|
|
pub enum Encodable {
|
||
|
|
Text(Option<String>),
|
||
|
|
Timestamp(Option<DateTime<Utc>>),
|
||
|
|
Uuid(Option<Uuid>),
|
||
|
|
}
|
||
|
|
|
||
|
|
impl Encodable {
|
||
|
|
// TODO: Can something similar be achieved with a generic return type?
|
||
|
|
/// Bind this as a parameter to a sqlx query.
|
||
|
|
pub fn bind_onto<'a>(
|
||
|
|
self,
|
||
|
|
query: sqlx::query::Query<'a, Postgres, <sqlx::Postgres as sqlx::Database>::Arguments<'a>>,
|
||
|
|
) -> sqlx::query::Query<'a, Postgres, <sqlx::Postgres as sqlx::Database>::Arguments<'a>> {
|
||
|
|
match self {
|
||
|
|
Self::Text(value) => query.bind(value),
|
||
|
|
Self::Timestamp(value) => query.bind(value),
|
||
|
|
Self::Uuid(value) => query.bind(value),
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Transform the contained value into a serde_json::Value.
|
||
|
|
pub fn inner_as_value(&self) -> serde_json::Value {
|
||
|
|
let serialized = serde_json::to_value(self).unwrap();
|
||
|
|
#[derive(Deserialize)]
|
||
|
|
struct Tagged {
|
||
|
|
c: serde_json::Value,
|
||
|
|
}
|
||
|
|
let deserialized: Tagged = serde_json::from_value(serialized).unwrap();
|
||
|
|
deserialized.c
|
||
|
|
}
|
||
|
|
|
||
|
|
pub fn is_none(&self) -> bool {
|
||
|
|
match self {
|
||
|
|
Self::Text(None) | Self::Timestamp(None) | Self::Uuid(None) => true,
|
||
|
|
Self::Text(_) | Self::Timestamp(_) | Self::Uuid(_) => false,
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|