Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

skeleton for openapi implementation #43

Draft
wants to merge 7 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion atelier-openapi/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -17,4 +17,12 @@ targets = ["x86_64-unknown-linux-gnu"]
all-features = true

[dependencies]
atelier_core = { version = "~0.2", path = "../atelier-core" }
atelier_core = { version = "~0.2", path = "../atelier-core" }
okapi = "0.7.0-rc.1"
serde_json = "1.0"

[dev-dependencies]
atelier_test = { version = "0.1", path = "../atelier-test" }
atelier_smithy = { version = "~0.2", path = "../atelier-smithy" }
atelier_json = { version = "~0.2", path = "../atelier-json" }
pretty_assertions = "1.1"
90 changes: 85 additions & 5 deletions atelier-openapi/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,18 +1,34 @@
/*!
Future home of the OpenAPI writer for Smithy.
use std::cell::RefCell;
use std::io::Write;
use std::str::FromStr;

*/

// use ...
use atelier_core::error::Error as ModelError;
use atelier_core::model::shapes::{AppliedTraits, Service};
use atelier_core::model::values::Value;
use atelier_core::model::visitor::walk_model;
use atelier_core::model::{Model, ShapeID};
use atelier_core::{io::ModelWriter, model::visitor::ModelVisitor};
use okapi::openapi3;
use serde_json::to_writer_pretty;

// ------------------------------------------------------------------------------------------------
// Public Types
// ------------------------------------------------------------------------------------------------

///
/// Writes out a model in the [OpenAPI](https://swagger.io/specification/) format.
///
#[derive(Debug, Default)]
pub struct OpenApiWriter {}

// ------------------------------------------------------------------------------------------------
// Private Types
// ------------------------------------------------------------------------------------------------

struct OpenApiModelVisitor {
spec: RefCell<openapi3::OpenApi>,
}

// ------------------------------------------------------------------------------------------------
// Public Functions
// ------------------------------------------------------------------------------------------------
Expand All @@ -21,10 +37,74 @@ Future home of the OpenAPI writer for Smithy.
// Implementations
// ------------------------------------------------------------------------------------------------

impl ModelWriter for OpenApiWriter {
fn write(&mut self, w: &mut impl Write, model: &Model) -> atelier_core::error::Result<()> {
let visitor = OpenApiModelVisitor {
spec: RefCell::new(openapi3::OpenApi {
openapi: "3.0.2".to_string(),
..openapi3::OpenApi::default()
}),
};
walk_model(model, &visitor)?;

to_writer_pretty(w, &visitor.spec.into_inner());

Ok(())
}
}

impl OpenApiModelVisitor {
fn add_info_object(&self, title: String, version: String) {
let mut spec = self.spec.borrow_mut();

spec.info = openapi3::Info {
version,
title,
..openapi3::Info::default()
};
}
}

impl ModelVisitor for OpenApiModelVisitor {
type Error = ModelError;

fn service(
&self,
id: &ShapeID,
traits: &AppliedTraits,
shape: &Service,
) -> Result<(), Self::Error> {
let title_trait_id = &ShapeID::from_str("smithy.api#title").unwrap();

let title = if traits.contains_key(title_trait_id) {
expect_string_trait_value(traits, title_trait_id)
} else {
Comment on lines +79 to +81
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

not sure if this is the best way to go about extracting traits. I'd like to is_titled but HasTraits is not implemented for Service. Not sure how this all fits together just yet

format!("{}", id.shape_name())
};

let version = shape.version().clone();

self.add_info_object(title, version);

Ok(())
}
}

// ------------------------------------------------------------------------------------------------
// Private Functions
// ------------------------------------------------------------------------------------------------

fn expect_string_trait_value(traits: &AppliedTraits, trait_id: &ShapeID) -> String {
if let Some(Some(trait_value)) = traits.get(trait_id) {
match trait_value {
Value::String(s) => s.clone(),
v => panic!("Expected trait {} to be a string but was: {}", trait_id, v),
}
} else {
panic!("Expected trait {} not found", trait_id)
}
}

// ------------------------------------------------------------------------------------------------
// Modules
// ------------------------------------------------------------------------------------------------
44 changes: 44 additions & 0 deletions atelier-openapi/tests/describe_openapi_writer.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
use atelier_core::io::{read_model_from_file, write_model_to_string};
use atelier_json::JsonReader;
use atelier_openapi::OpenApiWriter;
use atelier_smithy::SmithyReader;
use okapi::openapi3;
use pretty_assertions::assert_eq;
use std::{ffi::OsStr, fs, path::PathBuf};

#[test]
fn test_service() {
test("test-service.json");
}

#[test]
fn test_unions() {
test("union-test.smithy");
}

const MANIFEST_DIR: &str = env!("CARGO_MANIFEST_DIR");

// test helper which reads either a smithy idl file or smithy json file, converts it
// to openapi, and compares with the corresponding openapi spec from the /models directory.
fn test(file_name: &str) {
let source_file = PathBuf::from(format!("{}/tests/models/{}", MANIFEST_DIR, file_name));
let expected_file_path = source_file.with_extension("openapi.json");

let extension = source_file.extension().and_then(OsStr::to_str).unwrap();

let model = match extension {
"smithy" => read_model_from_file(&mut SmithyReader::default(), source_file),
"json" => read_model_from_file(&mut JsonReader::default(), source_file),
_ => panic!("test input extension must be .smithy or .json"),
}
.unwrap();

let mut writer = OpenApiWriter::default();
let actual_str = write_model_to_string(&mut writer, &model).unwrap();
let actual_spec: openapi3::OpenApi = serde_json::from_str(&actual_str).unwrap();

let expected_file = fs::read_to_string(expected_file_path).unwrap();
let expected_spec: openapi3::OpenApi = serde_json::from_str(&expected_file).unwrap();

assert_eq!(actual_spec, expected_spec);
}
Loading