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

Optional request bodies #5

Merged
merged 1 commit into from
Jan 7, 2025
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
65 changes: 61 additions & 4 deletions src/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,11 @@ pub(crate) struct Api {
}

impl Api {
pub(crate) fn new(paths: openapi::Paths, with_deprecated: bool) -> anyhow::Result<Self> {
pub(crate) fn new(
paths: openapi::Paths,
with_deprecated: bool,
component_schemas: &IndexMap<String, openapi::SchemaObject>,
) -> anyhow::Result<Self> {
let mut resources = BTreeMap::new();

for (path, pi) in paths {
Expand All @@ -46,7 +50,9 @@ impl Api {
continue;
}

if let Some((res_path, op)) = Operation::from_openapi(&path, method, op) {
if let Some((res_path, op)) =
Operation::from_openapi(&path, method, op, component_schemas)
{
let resource = get_or_insert_resource(&mut resources, res_path);
if op.method == "post" {
resource.has_post_operation = true;
Expand Down Expand Up @@ -223,6 +229,10 @@ struct Operation {
/// Name of the request body type, if any.
#[serde(skip_serializing_if = "Option::is_none")]
request_body_schema_name: Option<String>,
/// Some request bodies are required, but all the fields are optional (i.e. the CLI can omit
/// this from the argument list).
/// Only useful when `request_body_schema_name` is `Some`.
request_body_all_optional: bool,
/// Name of the response body type, if any.
#[serde(skip_serializing_if = "Option::is_none")]
response_body_schema_name: Option<String>,
Expand All @@ -234,6 +244,7 @@ impl Operation {
path: &str,
method: &str,
op: openapi::Operation,
component_schemas: &IndexMap<String, aide::openapi::SchemaObject>,
) -> Option<(Vec<String>, Self)> {
let Some(op_id) = op.operation_id else {
// ignore operations without an operationId
Expand Down Expand Up @@ -343,6 +354,51 @@ impl Operation {
}
}

let request_body_all_optional = op
.request_body
.as_ref()
.map(|r| {
match r {
ReferenceOr::Reference { .. } => {
unimplemented!("reference")
}
ReferenceOr::Item(body) => {
if let Some(mt) = body.content.get("application/json") {
match mt.schema.as_ref().map(|so| &so.json_schema) {
Some(Schema::Object(schemars::schema::SchemaObject {
object: Some(ov),
..
})) => {
return ov.required.is_empty();
}
Some(Schema::Object(schemars::schema::SchemaObject {
reference: Some(s),
..
})) => {
match component_schemas
.get(
&get_schema_name(Some(s)).expect("schema should exist"),
)
.map(|so| &so.json_schema)
{
Some(Schema::Object(schemars::schema::SchemaObject {
object: Some(ov),
..
})) => {
return ov.required.is_empty();
}
_ => unimplemented!("double ref not supported"),
}
}
_ => {}
}
}
}
}
false
})
.unwrap_or_default();

let request_body_schema_name = op.request_body.and_then(|b| match b {
ReferenceOr::Item(mut req_body) => {
assert!(req_body.required);
Expand All @@ -362,7 +418,7 @@ impl Operation {
if !obj.is_ref() {
tracing::error!(?obj, "unexpected non-$ref json body schema");
}
get_schema_name(obj.reference)
get_schema_name(obj.reference.as_deref())
}
}
}
Expand Down Expand Up @@ -415,6 +471,7 @@ impl Operation {
header_params,
query_params,
request_body_schema_name,
request_body_all_optional,
response_body_schema_name,
};
Some((res_path, op))
Expand Down Expand Up @@ -458,7 +515,7 @@ fn response_body_schema_name(resp: ReferenceOr<openapi::Response>) -> Option<Str
if !obj.is_ref() {
tracing::error!(?obj, "unexpected non-$ref json body schema");
}
get_schema_name(obj.reference)
get_schema_name(obj.reference.as_deref())
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ fn main() -> anyhow::Result<()> {
let mut components = spec.components.unwrap_or_default();

if let Some(paths) = spec.paths {
let api = Api::new(paths, with_deprecated).unwrap();
let api = Api::new(paths, with_deprecated, &components.schemas).unwrap();
{
let mut api_file = BufWriter::new(File::create("api.ron")?);
writeln!(api_file, "{api:#?}")?;
Expand Down
2 changes: 1 addition & 1 deletion src/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ impl FieldType {
Some(SingleOrVec::Vec(types)) => {
bail!("unsupported multi-typed parameter: `{types:?}`")
}
None => match get_schema_name(obj.reference) {
None => match get_schema_name(obj.reference.as_deref()) {
Some(name) => Self::SchemaRef(name),
None => bail!("unsupported type-less parameter"),
},
Expand Down
2 changes: 1 addition & 1 deletion src/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use std::{collections::BTreeSet, io, process::Command, sync::Mutex};

use camino::Utf8Path;

pub(crate) fn get_schema_name(maybe_ref: Option<String>) -> Option<String> {
pub(crate) fn get_schema_name(maybe_ref: Option<&str>) -> Option<String> {
let r = maybe_ref?;
let schema_name = r.strip_prefix("#/components/schemas/");
if schema_name.is_none() {
Expand Down
15 changes: 13 additions & 2 deletions templates/svix_cli_resource.rs.jinja
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,12 @@ pub enum {{ resource_type_name }}Commands {
{# body parameter struct -#}
{% if op.request_body_schema_name is defined -%}
{{ op.request_body_schema_name | to_snake_case }}:
JsonOf<{{ op.request_body_schema_name }}>,
{% if op.request_body_all_optional %}
Option<JsonOf<{{ op.request_body_schema_name }}>>
{% else %}
JsonOf<{{ op.request_body_schema_name }}>
{% endif %}
,
{% endif -%}

{# query parameters -#}
Expand Down Expand Up @@ -151,7 +156,13 @@ impl {{ resource_type_name }}Commands {

{# body parameter struct -#}
{% if op.request_body_schema_name is defined -%}
{{ op.request_body_schema_name | to_snake_case }}.into_inner(),
{{ op.request_body_schema_name | to_snake_case }}
{% if op.request_body_all_optional -%}
.map(|x| x.into_inner()).unwrap_or_default()
{% else -%}
.into_inner()
{% endif -%}
,
{% endif -%}

{# query parameters -#}
Expand Down