Skip to content

Commit f0d7874

Browse files
committed
refactor(api-spec): add a light internal api to isolate openai spec parsing
So it's easier to change it, or maybe add another file format, if needed.
1 parent 5848ef5 commit f0d7874

File tree

4 files changed

+27
-7
lines changed

4 files changed

+27
-7
lines changed

internal/tests/mithril-api-spec/src/apispec.rs

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ use warp::http::Response;
88
use warp::http::StatusCode;
99
use warp::hyper::body::Bytes;
1010

11-
use crate::yaml_to_serde::convert_yaml_to_serde_json;
11+
use crate::spec_parser::OpenApiSpecParser;
1212

1313
#[cfg(test)]
1414
pub(crate) const DEFAULT_SPEC_FILE: &str = "../../../openapi.yaml";
@@ -56,12 +56,8 @@ impl<'a> APISpec<'a> {
5656

5757
/// APISpec factory from spec
5858
pub fn from_file(path: &str) -> APISpec<'a> {
59-
use saphyr::LoadableYamlNode;
60-
61-
let yaml_spec = std::fs::read_to_string(path).unwrap();
62-
let openapi = saphyr::Yaml::load_from_str(&yaml_spec).unwrap();
6359
APISpec {
64-
openapi: convert_yaml_to_serde_json(&openapi[0]).unwrap(),
60+
openapi: OpenApiSpecParser::parse_yaml(path).unwrap(),
6561
path: None,
6662
method: None,
6763
content_type: Some("application/json"),

internal/tests/mithril-api-spec/src/lib.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
//! This crate provides a toolset to verify conformity of http routes against an Open Api specification.
33
44
mod apispec;
5-
mod yaml_to_serde;
5+
pub(crate) mod spec_parser;
66

77
pub use apispec::*;
88

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
mod yaml;
2+
3+
/// Parser for OpenApi Specification
4+
///
5+
/// Returns the parsed spec as a [serde_json::Value] as this crate uses a jsonschema validator
6+
/// to do the validation.
7+
pub(crate) struct OpenApiSpecParser;
8+
9+
impl OpenApiSpecParser {
10+
pub(crate) fn parse_yaml(spec_path: &str) -> Result<serde_json::Value, String> {
11+
use saphyr::LoadableYamlNode;
12+
13+
let yaml_spec = std::fs::read_to_string(spec_path)
14+
.map_err(|e| format!("Could not read spec file `{spec_path}`: {e}"))?;
15+
let openapi = saphyr::Yaml::load_from_str(&yaml_spec)
16+
.map_err(|e| format!("Could not parse spec file `{spec_path}`: {e}"))?;
17+
18+
if openapi.is_empty() {
19+
Err("No spec found in file".to_string())
20+
} else {
21+
yaml::convert_yaml_to_serde_json(&openapi[0])
22+
}
23+
}
24+
}
File renamed without changes.

0 commit comments

Comments
 (0)