use http::StatusCode;
use serde::Serialize;
use serde_json::Value;
use crate::response::{IntoResponse, Status};
#[derive(Serialize)]
pub struct Fail {
status: Status,
data: Value,
#[serde(skip)]
http_status: StatusCode,
}
impl Fail {
pub fn new<I, K, V>(data: I, http_status: StatusCode) -> Self
where
I: IntoIterator<Item = (K, V)>,
K: Into<String>,
V: Into<Value>,
{
let fail_data: serde_json::Map<String, Value> = data
.into_iter()
.map(|(k, v)| (k.into(), v.into()))
.collect();
Self {
status: Status::Fail,
data: Value::Object(fail_data),
http_status,
}
}
pub fn status(&self) -> &Status {
&self.status
}
pub fn data(&self) -> &Value {
&self.data
}
}
impl IntoResponse for Fail {
fn http_status(&self) -> StatusCode {
self.http_status
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::{from_slice, json};
fn to_json<R: IntoResponse + Serialize>(response: R) -> Value {
let http_response = response
.into_response()
.expect("serialisation should succeed");
from_slice(http_response.body()).expect("body should be valid JSON")
}
#[test]
fn builds_data_object_from_pairs() {
let response = Fail::new(
[("title", "is required"), ("duration", "must be positive")],
StatusCode::UNPROCESSABLE_ENTITY,
);
let body = to_json(response);
assert_eq!(body["status"], "fail");
assert_eq!(body["data"]["title"], "is required");
}
#[test]
fn accepts_non_string_values() {
let response = Fail::new(
[("duration", json!(-5))],
StatusCode::UNPROCESSABLE_ENTITY,
);
let body = to_json(response);
assert_eq!(body["data"]["duration"], -5);
}
#[test]
fn no_entries_serialises_empty_object() {
let response =
Fail::new(Vec::<(&str, &str)>::new(), StatusCode::BAD_REQUEST);
assert_eq!(to_json(response)["data"], json!({}));
}
#[test]
fn status_is_fail() {
let response = Fail::new(
[("title", "is required"), ("duration", "must be positive")],
StatusCode::UNPROCESSABLE_ENTITY,
);
assert_eq!(response.status(), &Status::Fail);
}
#[test]
fn data_returns_constructed_object() {
let response = Fail::new(
[("title", "is required"), ("duration", "must be positive")],
StatusCode::UNPROCESSABLE_ENTITY,
);
assert_eq!(
response.data(),
&json!({"title": "is required", "duration": "must be positive"})
);
}
}