openapi3_parser/
lib.rs

1pub mod open_api;
2use open_api::OpenApiSpec;
3use serde::{Deserialize, Serialize};
4use std::fs::File;
5use std::io::Read;
6use std::path::Path;
7use thiserror::Error;
8
9#[derive(Debug, Error)]
10pub enum OpenApiError {
11    #[error("Failed to read file: {0}")]
12    ReadError(#[from] std::io::Error),
13
14    #[error("Failed to parse JSON: {0}")]
15    JsonParseError(#[from] serde_json::Error),
16
17    #[error("Failed to parse YAML: {0}")]
18    YamlParseError(#[from] serde_yaml::Error),
19
20    #[error("Unsupported file format. Only .json and .yaml/.yml files are supported.")]
21    UnsupportedFormat,
22}
23
24// Enum to handle supported file types
25enum FileType {
26    Json,
27    Yaml,
28}
29
30/// Determines the file type based on the file extension (.json or .yaml)
31fn determine_file_type(file_path: &Path) -> Result<FileType, OpenApiError> {
32    match file_path.extension().and_then(|ext| ext.to_str()) {
33        Some("json") => Ok(FileType::Json),
34        Some("yaml") | Some("yml") => Ok(FileType::Yaml),
35        _ => Err(OpenApiError::UnsupportedFormat),
36    }
37}
38
39/// Parses a JSON or YAML OpenAPI specification file into the OpenAPI struct
40pub fn parse_openapi_file(file_path: &str) -> Result<OpenApiSpec, OpenApiError> {
41    // Determine the file type (JSON or YAML)
42    let file_type = determine_file_type(Path::new(file_path))?;
43
44    // Read the file contents
45    let mut file = File::open(file_path)?;
46    let mut contents = String::new();
47    file.read_to_string(&mut contents)?;
48
49    // Parse the file based on its type
50    match file_type {
51        FileType::Json => {
52            let openapi: OpenApiSpec = serde_json::from_str(&contents)?;
53            Ok(openapi)
54        }
55        FileType::Yaml => {
56            let openapi: OpenApiSpec = serde_yaml::from_str(&contents)?;
57            Ok(openapi)
58        }
59    }
60}
61
62#[cfg(test)]
63mod tests {
64    use super::*;
65
66    #[test]
67    fn test_parse_json() {
68        let result = parse_openapi_file("test-data/openapi.json");
69        println!("{:?}", result);
70        assert!(result.is_ok());
71    }
72
73    #[test]
74    fn test_parse_yaml() {
75        let result = parse_openapi_file("test-data/openapi.yaml");
76        assert!(result.is_ok());
77    }
78}