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

Feat: add example to schema definition #421

Merged
merged 3 commits into from
May 1, 2022
Merged
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
6 changes: 5 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,12 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [0.7.1] - 2022-04-10
## [Unreleased]
### Added
- Add example support for derived `Apiv2Schema`. [PR#421](https://github.com/paperclip-rs/paperclip/pull/421)

### Fixed
- Fix missing slashed between url parts [PR#416](https://github.com/paperclip-rs/paperclip/pull/416)
- Properly support non-BoxBody response payload types [PR#414](https://github.com/paperclip-rs/paperclip/pull/414)
- Fix required fields definition when using serde flatten [PR#412](https://github.com/paperclip-rs/paperclip/pull/412)
- Fix reference urls not being RFC3986-compliant [PR#411](https://github.com/paperclip-rs/paperclip/pull/411)
Expand Down
6 changes: 1 addition & 5 deletions core/src/v3/schema.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,11 +25,7 @@ impl From<v2::DefaultSchemaRaw> for openapiv3::ReferenceOr<openapiv3::Schema> {
write_only: false,
deprecated: false,
external_docs: None,
example: if let Some(example) = v2.example {
serde_json::from_str(&example).ok()
} else {
None
},
example: v2.example,
title: v2.title,
description: v2.description,
discriminator: None,
Expand Down
46 changes: 46 additions & 0 deletions macros/src/actix.rs
Original file line number Diff line number Diff line change
Expand Up @@ -688,6 +688,29 @@ fn extract_rename(attrs: &[Attribute]) -> Option<String> {
None
}

fn extract_example(attrs: &[Attribute]) -> Option<String> {
let attrs = extract_openapi_attrs(attrs);
for attr in attrs.flat_map(|attr| attr.into_iter()) {
if let NestedMeta::Meta(Meta::NameValue(nv)) = attr {
if nv.path.is_ident("example") {
if let Lit::Str(s) = nv.lit {
return Some(s.value());
} else {
emit_error!(
nv.lit.span().unwrap(),
format!(
"`#[{}(example = \"...\")]` expects a string argument",
SCHEMA_MACRO_ATTR
),
);
}
}
}
}

None
}

/// Actual parser and emitter for `api_v2_schema` macro.
pub fn emit_v2_definition(input: TokenStream) -> TokenStream {
let item_ast = match crate::expect_struct_or_enum(input) {
Expand All @@ -702,6 +725,17 @@ pub fn emit_v2_definition(input: TokenStream) -> TokenStream {
let docs = extract_documentation(&item_ast.attrs);
let docs = docs.trim();

let example = if let Some(example) = extract_example(&item_ast.attrs) {
// allow to parse escaped json string or single str value
quote!(
serde_json::from_str::<serde_json::Value>(#example).ok().or_else(|| Some(#example.into()))
)
} else {
quote!(None)
};

eprintln!("{}", example);

let props = SerdeProps::from_item_attrs(&item_ast.attrs);

let name = &item_ast.ident;
Expand Down Expand Up @@ -768,6 +802,7 @@ pub fn emit_v2_definition(input: TokenStream) -> TokenStream {
let default_schema_raw_def = quote! {
let mut schema = DefaultSchemaRaw {
name: Some(#schema_name.into()),
example: #example,
..Default::default()
};
};
Expand All @@ -776,6 +811,7 @@ pub fn emit_v2_definition(input: TokenStream) -> TokenStream {
let default_schema_raw_def = quote! {
let mut schema = DefaultSchemaRaw {
name: Some(Self::__paperclip_schema_name()), // Add name for later use.
example: #example,
.. Default::default()
};
};
Expand Down Expand Up @@ -1255,12 +1291,22 @@ fn handle_field_struct(
let docs = extract_documentation(&field.attrs);
let docs = docs.trim();

let example = if let Some(example) = extract_example(&field.attrs) {
// allow to parse escaped json string or single str value
quote!({
s.example = serde_json::from_str::<serde_json::Value>(#example).ok().or_else(|| Some(#example.into()));
})
} else {
quote!({})
};

let mut gen = if !SerdeFlatten::exists(&field.attrs) {
quote!({
let mut s = #ty_ref::raw_schema();
if !#docs.is_empty() {
s.description = Some(#docs.to_string());
}
#example;
schema.properties.insert(#field_name.into(), s.into());

if #ty_ref::required() {
Expand Down
2 changes: 1 addition & 1 deletion macros/src/core.rs
Original file line number Diff line number Diff line change
Expand Up @@ -286,7 +286,7 @@ fn schema_fields(name: &Ident, is_ref: bool) -> proc_macro2::TokenStream {
));
gen.extend(quote!(
#[serde(skip_serializing_if = "Option::is_none")]
pub example: Option<String>,
pub example: Option<serde_json::Value>,
));

gen.extend(quote!(
Expand Down
128 changes: 128 additions & 0 deletions tests/test_app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3906,6 +3906,134 @@ fn test_rename() {
);
}

#[test]
fn test_example() {
#[derive(Deserialize, Serialize, Apiv2Schema)]
#[openapi(example = r#"{ "name": "Rex", "age": 8 }"#)]
/// Pets are awesome!
struct Pet {
/// Pick a good one.
name: String,
/// 7 time yours
age: u8,
}

#[derive(Deserialize, Serialize, Apiv2Schema)]
struct Car {
/// Pick a good one.
#[openapi(example = "whatever")]
name: String,
}

#[api_v2_operation]
fn echo_pets() -> impl Future<Output = Result<web::Json<Vec<Pet>>, Error>> {
fut_ok(web::Json(vec![]))
}

#[api_v2_operation]
fn echo_cars() -> impl Future<Output = Result<web::Json<Vec<Car>>, Error>> {
fut_ok(web::Json(vec![]))
}

run_and_check_app(
|| {
App::new()
.wrap_api()
.route("/pets", web::get().to(echo_pets))
.route("/cars", web::get().to(echo_cars))
.with_json_spec_at("/api/spec")
.build()
},
|addr| {
let resp = CLIENT
.get(&format!("http://{}/api/spec", addr))
.send()
.expect("request failed?");

check_json(
resp,
json!({
"definitions": {
"Car": {
"properties": {
"name": {
"description": "Pick a good one.",
"example": "whatever",
"type": "string"
}
},
"required": [
"name"
],
"type": "object"
},
"Pet": {
"description": "Pets are awesome!",
"example": {
"age": 8,
"name": "Rex"
},
"properties": {
"age": {
"description": "7 time yours",
"format": "int32",
"type": "integer"
},
"name": {
"description": "Pick a good one.",
"type": "string"
}
},
"required": [
"age",
"name"
],
"type": "object"
}
},
"info": {
"title": "",
"version": ""
},
"paths": {
"/cars": {
"get": {
"responses": {
"200": {
"description": "OK",
"schema": {
"items": {
"$ref": "#/definitions/Car"
},
"type": "array"
}
}
}
}
},
"/pets": {
"get": {
"responses": {
"200": {
"description": "OK",
"schema": {
"items": {
"$ref": "#/definitions/Pet"
},
"type": "array"
}
}
}
}
}
},
"swagger": "2.0"
}),
);
},
);
}

mod module_path_in_definition_name {
pub mod foo {
pub mod bar {
Expand Down