rjapi 0.0.1

A framework-agnostic JSON:API 1.1 implementation for Rust
Documentation
//! JSON:API Middleware Utilities
//!
//! This module provides framework-agnostic middleware utilities for JSON:API implementations.
//! These functions can be used with any Rust web framework to ensure JSON:API compliance.

use http;

/// JSON:API Content-Type validator
///
/// Ensures requests have the correct Content-Type for JSON:API.
/// According to the JSON:API specification, requests with content bodies MUST use the
/// `application/vnd.api+json` media type.
///
/// # Arguments
///
/// * `method` - The HTTP method of the request
/// * `headers` - The headers of the request
///
/// # Returns
///
/// * `Ok(())` if the Content-Type is valid or not required
/// * `Err((status, headers, message))` if the Content-Type is invalid
///
/// # Example
///
/// ```rust
/// use http::Request;
/// use rjapi::middleware::validate_content_type;
///
/// let mut req = Request::builder().method("POST").body(()).unwrap();
/// req.headers_mut().insert("content-type", "application/vnd.api+json".parse().unwrap());
/// assert!(validate_content_type(&req).is_ok());
/// ```
use crate::JsonApiErrorResponse;

pub fn validate_content_type<B>(req: &http::Request<B>) -> Result<(), JsonApiErrorResponse> {
    if req.method() == http::Method::POST || req.method() == http::Method::PATCH {
        let content_type = req.headers().get(http::header::CONTENT_TYPE);
        if content_type.is_none() || content_type.unwrap() != "application/vnd.api+json" {
            return Err(crate::bad_request_error(
                "Unsupported Media Type",
                "Content-Type must be application/vnd.api+json",
            ));
        }
    }
    Ok(())
}

pub fn set_content_type<B>(res: &mut http::Response<B>) {
    res.headers_mut().insert(
        http::header::CONTENT_TYPE,
        "application/vnd.api+json".parse().unwrap(),
    );
}