use serde::Serialize;
use serde_json::{Map, Value as Json};
use crate::db::{ToValue, Value};
use crate::model::Model;
use crate::response::{IntoStatus, Response};
pub trait Serializer {
type Model;
fn serialize(record: &Self::Model) -> Json;
fn root() -> String {
let name = std::any::type_name::<Self::Model>();
let name = name.rsplit("::").next().unwrap_or(name);
glacier_inflect::snake_case(name)
}
fn root_many() -> String {
glacier_inflect::pluralize(&Self::root())
}
fn one(record: &Self::Model) -> Json {
Self::serialize(record)
}
fn schema() -> Json {
serde_json::json!({"type": "object"})
}
fn many(records: &[Self::Model]) -> Json {
Json::Array(records.iter().map(Self::serialize).collect())
}
}
pub fn attributes<M: Model>(record: &M) -> Json {
let mut object = Map::new();
for (column, value) in record.values() {
object.insert(column.to_owned(), value_json(&value));
}
Json::Object(object)
}
pub fn root(name: &str, value: Json) -> Json {
let mut object = Map::new();
object.insert(name.to_owned(), value);
Json::Object(object)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TimeFormat {
Iso8601,
UnixSeconds,
}
static UNIX_SECONDS: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
pub fn set_time_format(format: TimeFormat) {
UNIX_SECONDS.store(
format == TimeFormat::UnixSeconds,
std::sync::atomic::Ordering::Relaxed,
);
}
fn time_format() -> TimeFormat {
if UNIX_SECONDS.load(std::sync::atomic::Ordering::Relaxed) {
TimeFormat::UnixSeconds
} else {
TimeFormat::Iso8601
}
}
pub fn value_json(value: &Value) -> Json {
match value {
Value::Null => Json::Null,
Value::Bool(b) => Json::Bool(*b),
Value::Int(i) => Json::from(*i),
Value::Float(f) => serde_json::Number::from_f64(*f).map_or(Json::Null, Json::Number),
Value::Text(s) => Json::String(s.clone()),
Value::Bytes(b) => Json::String(String::from_utf8_lossy(b).into_owned()),
Value::Timestamp(t) => match time_format() {
TimeFormat::Iso8601 => Json::String(t.format("%Y-%m-%dT%H:%M:%S%.3fZ").to_string()),
TimeFormat::UnixSeconds => Json::from(t.timestamp()),
},
Value::Date(d) => Json::String(d.format("%Y-%m-%d").to_string()),
Value::Json(json) => json.clone(),
Value::Decimal(d) => Json::String(d.to_string()),
Value::Uuid(u) => Json::String(u.to_string()),
Value::List(items) => Json::Array(items.iter().map(value_json).collect()),
}
}
pub struct Render<'a, T: ?Sized> {
value: &'a T,
status: Option<http::StatusCode>,
root: Option<Root>,
page: Option<(crate::pagination::Page, u64)>,
headers: Vec<(String, String)>,
}
pub struct Rendered {
json: Json,
status: Option<http::StatusCode>,
root: Option<String>,
page: Option<(crate::pagination::Page, u64)>,
headers: Vec<(String, String)>,
}
#[doc(hidden)]
pub enum Root {
Key(String),
None,
}
#[doc(hidden)]
pub trait IntoRoot {
fn into_root(self) -> Root;
}
impl IntoRoot for &str {
fn into_root(self) -> Root {
Root::Key(self.to_owned())
}
}
impl IntoRoot for String {
fn into_root(self) -> Root {
Root::Key(self)
}
}
impl IntoRoot for bool {
fn into_root(self) -> Root {
if self {
Root::Key(String::new())
} else {
Root::None
}
}
}
impl<'a, T: ?Sized> Render<'a, T> {
pub fn new(value: &'a T) -> Self {
Self {
value,
status: None,
root: None,
page: None,
headers: Vec::new(),
}
}
pub fn header(mut self, (name, value): (impl Into<String>, impl Into<String>)) -> Self {
self.headers.push((name.into(), value.into()));
self
}
pub fn cursor<M>(mut self, page: &crate::pagination::Cursored<M>) -> Self {
self.headers
.extend(page.link().map(|link| ("link".to_owned(), link)));
self
}
pub fn paginate(mut self, (page, total): (crate::pagination::Page, impl TryInto<u64>)) -> Self {
self.page = Some((page, total.try_into().unwrap_or(0)));
self
}
pub fn status(mut self, status: impl IntoStatus) -> Self {
self.status = Some(status.into_status());
self
}
pub fn root(mut self, root: impl IntoRoot) -> Self {
self.root = Some(root.into_root());
self
}
pub fn each_serializer<S: Serializer>(self, _: S) -> Rendered
where
T: AsRef<[S::Model]>,
{
let json = S::many(self.value.as_ref());
self.rendered(json, S::root_many())
}
pub fn serializer<S: Serializer>(self, _: S) -> Rendered
where
T: std::borrow::Borrow<S::Model>,
{
let json = S::one(self.value.borrow());
self.rendered(json, S::root())
}
fn rendered(self, json: Json, default_root: String) -> Rendered {
let root = match self.root {
None => Some(default_root),
Some(Root::Key(key)) if key.is_empty() => Some(default_root),
Some(Root::Key(key)) => Some(key),
Some(Root::None) => None,
};
Rendered {
json,
status: self.status,
root,
page: self.page,
headers: self.headers,
}
}
pub fn respond(self) -> crate::Result<Response>
where
T: Serialize,
{
let json = serde_json::to_value(self.value)?;
let json = match self.root {
Some(Root::Key(key)) if !key.is_empty() => root(&key, json),
_ => json,
};
Ok(respond(&json, self.status, self.page, self.headers))
}
}
impl Rendered {
pub fn header(mut self, (name, value): (impl Into<String>, impl Into<String>)) -> Self {
self.headers.push((name.into(), value.into()));
self
}
pub fn status(mut self, status: impl IntoStatus) -> Self {
self.status = Some(status.into_status());
self
}
pub fn paginate(mut self, (page, total): (crate::pagination::Page, impl TryInto<u64>)) -> Self {
self.page = Some((page, total.try_into().unwrap_or(0)));
self
}
pub fn cursor<M>(mut self, page: &crate::pagination::Cursored<M>) -> Self {
self.headers
.extend(page.link().map(|link| ("link".to_owned(), link)));
self
}
pub fn root(mut self, key: impl IntoRoot) -> Self {
match key.into_root() {
Root::Key(key) if key.is_empty() => {}
Root::Key(key) => self.root = Some(key),
Root::None => self.root = None,
}
self
}
pub fn respond(self) -> crate::Result<Response> {
let json = match self.root {
Some(key) => root(&key, self.json),
None => self.json,
};
Ok(respond(&json, self.status, self.page, self.headers))
}
}
fn respond(
json: &Json,
status: Option<http::StatusCode>,
page: Option<(crate::pagination::Page, u64)>,
headers: Vec<(String, String)>,
) -> Response {
let mut response = Response::json(json);
for (name, value) in headers {
response = response.with_header(name, value);
}
if let Some(status) = status {
response = response.with_status(status);
}
match page {
Some((page, total)) => page.headers(total, response),
None => response,
}
}
#[derive(Default)]
pub struct Object(Map<String, Json>, bool);
impl Object {
pub fn new() -> Self {
Self::default()
}
pub fn schema() -> Self {
Self(Map::new(), true)
}
#[doc(hidden)]
pub fn field(
&mut self,
name: &str,
value: impl FnOnce() -> Json,
schema: impl FnOnce() -> Json,
) -> &mut Self {
let json = if self.1 { schema() } else { value() };
self.0.insert(name.to_owned(), json);
self
}
pub fn attr(&mut self, name: &str, value: &impl ToValue) -> &mut Self {
self.0
.insert(name.to_owned(), value_json(&value.to_value()));
self
}
pub fn value(&mut self, name: &str, value: &impl Serialize) -> &mut Self {
let json = serde_json::to_value(value).unwrap_or(Json::Null);
self.0.insert(name.to_owned(), json);
self
}
pub fn json(&mut self, name: &str, value: Json) -> &mut Self {
self.0.insert(name.to_owned(), value);
self
}
pub fn many<M>(
&mut self,
name: &str,
records: Option<&[M]>,
serialize: impl Fn(&M) -> Json,
) -> &mut Self {
let json = records.map_or(Json::Null, |records| {
Json::Array(records.iter().map(serialize).collect())
});
self.json(name, json)
}
pub fn one<M>(
&mut self,
name: &str,
record: Option<&M>,
serialize: impl Fn(&M) -> Json,
) -> &mut Self {
let json = record.map_or(Json::Null, serialize);
self.json(name, json)
}
pub fn into_json(self) -> Json {
if self.1 {
let required: Vec<&String> = self.0.keys().collect();
let required = serde_json::json!(required);
return serde_json::json!({
"type": "object",
"properties": Json::Object(self.0),
"required": required,
});
}
Json::Object(self.0)
}
}
pub trait Schema {
fn schema() -> Json;
}
macro_rules! schema {
($schema:tt: $($ty:ty),*) => {
$(impl Schema for $ty {
fn schema() -> Json {
serde_json::json!($schema)
}
})*
};
}
schema!({"type": "integer", "format": "int32"}: i8, i16, i32, u8, u16);
schema!({"type": "integer", "format": "int64"}: i64, u32, u64, isize, usize);
schema!({"type": "number"}: f32, f64);
schema!({"type": "boolean"}: bool);
schema!({"type": "string"}: String, str, char);
schema!({"type": "string", "format": "decimal"}: crate::db::Decimal);
schema!({"type": "string", "format": "date-time"}: crate::db::Timestamp, crate::db::NaiveTimestamp);
schema!({"type": "string", "format": "date"}: crate::db::Date);
schema!({"type": "string", "format": "uuid"}: crate::db::Uuid);
schema!({}: Json);
impl<T: Schema + ?Sized> Schema for &T {
fn schema() -> Json {
T::schema()
}
}
impl<T: Schema + ?Sized> Schema for Box<T> {
fn schema() -> Json {
T::schema()
}
}
impl<T: Schema> Schema for Option<T> {
fn schema() -> Json {
nullable(T::schema())
}
}
impl<T: Schema> Schema for Vec<T> {
fn schema() -> Json {
serde_json::json!({"type": "array", "items": T::schema()})
}
}
impl<T: Schema> Schema for [T] {
fn schema() -> Json {
serde_json::json!({"type": "array", "items": T::schema()})
}
}
pub fn nullable(schema: Json) -> Json {
match schema {
Json::Object(mut object) => match object.get("type").cloned() {
Some(Json::String(ty)) => {
object.insert("type".to_owned(), serde_json::json!([ty, "null"]));
Json::Object(object)
}
_ if object.is_empty() => Json::Object(object),
_ => serde_json::json!({"anyOf": [Json::Object(object), {"type": "null"}]}),
},
other => other,
}
}
#[doc(hidden)]
pub struct Probe<T>(std::marker::PhantomData<fn() -> T>);
impl<T> Probe<T> {
pub fn of(_value: impl FnOnce() -> T) -> Self {
Self(std::marker::PhantomData)
}
pub fn new() -> Self {
Self(std::marker::PhantomData)
}
}
impl<T> Default for Probe<T> {
fn default() -> Self {
Self::new()
}
}
#[doc(hidden)]
pub trait ProbeSchema {
fn schema(&self) -> Json;
}
impl<T: Schema> ProbeSchema for &Probe<T> {
fn schema(&self) -> Json {
T::schema()
}
}
#[doc(hidden)]
pub trait ProbeAny {
fn schema(&self) -> Json;
}
impl<T> ProbeAny for Probe<T> {
fn schema(&self) -> Json {
serde_json::json!({})
}
}
#[doc(hidden)]
pub fn attr_json(value: &impl ToValue) -> Json {
value_json(&value.to_value())
}
#[doc(hidden)]
pub fn value_to_json(value: &impl Serialize) -> Json {
serde_json::to_value(value).unwrap_or(Json::Null)
}
#[doc(hidden)]
pub fn one_json<M>(record: Option<&M>, serialize: impl Fn(&M) -> Json) -> Json {
record.map_or(Json::Null, serialize)
}
#[doc(hidden)]
pub fn many_json<M>(records: Option<&[M]>, serialize: impl Fn(&M) -> Json) -> Json {
records.map_or(Json::Null, |records| {
Json::Array(records.iter().map(serialize).collect())
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn writes_values_as_rails_does() {
let at = chrono::NaiveDate::from_ymd_opt(2024, 1, 2)
.unwrap()
.and_hms_milli_opt(10, 0, 0, 5)
.unwrap()
.and_utc();
assert_eq!(
value_json(&Value::Timestamp(at)),
"2024-01-02T10:00:00.005Z"
);
let mut object = Object::new();
object
.attr("zeta", &1)
.attr("alpha", &Some("a".to_owned()))
.attr("none", &None::<i32>);
assert_eq!(
serde_json::to_string(&object.into_json()).unwrap(),
r#"{"zeta":1,"alpha":"a","none":null}"#,
"keys stay in the order written"
);
assert_eq!(
root("items", Json::Array(vec![])),
serde_json::json!({"items": []})
);
}
#[test]
fn root_keys_come_from_the_model_name() {
struct FaqSection;
struct FaqSectionSerializer;
impl Serializer for FaqSectionSerializer {
type Model = FaqSection;
fn serialize(_: &FaqSection) -> Json {
Json::Null
}
}
assert_eq!(FaqSectionSerializer::root(), "faq_section");
assert_eq!(FaqSectionSerializer::root_many(), "faq_sections");
}
}