swarm / companies/starter/work/project/src/sync/fhir_validator.rs

raw file 1164 bytes
use serde_json::Value;

pub struct FhirValidationError {
    pub field: String,
    pub message: String,
}

pub fn validate_inbound_fhir(payload: &Value) -> Result<(), FhirValidationError> {
    let obj = payload.as_object().ok_or_else(|| FhirValidationError {
        field: "root".to_string(),
        message: "Payload is not a JSON object".to_string(),
    })?;

    let resource_type = obj.get("resourceType").and_then(|v| v.as_str());

    if resource_type.is_none() {
        return Err(FhirValidationError {
            field: "resourceType".to_string(),
            message: "Missing required field 'resourceType'".to_string(),
        });
    }

    // Basic check: if it's a Patient, it must have an id (though id can be empty in some drafts, 
    // for our sync we require a stable identifier)
    if resource_type == Some("Patient") {
        let id = obj.get("id").and_then(|v| v.as_str());
        if id.is_none() || id.is_empty() {
            return Err(FhirValidationError {
                field: "id".to_string(),
                message: "Patient resource must have a non-empty 'id'".to_string(),
            });
        }
    }

    Ok(())
}