rjango 0.1.1

A full-stack Rust backend framework inspired by Django
Documentation
//! JSON response helpers.

use http::StatusCode;
use serde::Serialize;

use crate::http::HttpResponse;

/// Create a JSON response with 200 OK status.
pub fn json_response<T: Serialize>(data: &T) -> HttpResponse {
    let body = serde_json::to_string(data).unwrap_or_default();
    let mut resp = HttpResponse::with_status(StatusCode::OK, body);
    resp.set_header(http::header::CONTENT_TYPE, "application/json");
    resp
}

/// Create a JSON response with a custom status code.
pub fn json_response_with_status<T: Serialize>(data: &T, status: StatusCode) -> HttpResponse {
    let body = serde_json::to_string(data).unwrap_or_default();
    let mut resp = HttpResponse::with_status(status, body);
    resp.set_header(http::header::CONTENT_TYPE, "application/json");
    resp
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    #[test]
    fn json_response_ok() {
        let resp = json_response(&json!({"key": "value"}));
        assert_eq!(resp.status_code, StatusCode::OK);
        let body = std::str::from_utf8(&resp.content).unwrap();
        assert!(body.contains("key"));
    }

    #[test]
    fn json_response_custom_status() {
        let resp = json_response_with_status(&json!({"error": "nope"}), StatusCode::BAD_REQUEST);
        assert_eq!(resp.status_code, StatusCode::BAD_REQUEST);
    }

    #[test]
    fn json_response_content_type() {
        let resp = json_response(&json!({}));
        let ct = resp.headers.get(http::header::CONTENT_TYPE).unwrap();
        assert_eq!(ct, "application/json");
    }
}