cinderblock-json-api 0.7.0

JSON REST API extension for cinderblock with Axum router, auto-registered endpoints, and OpenAPI support
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
//! JSON REST API extension for cinderblock resources.
//!
//! When a resource declares `cinderblock_json_api` in its `extensions { ... }`
//! block, the [`resource!`](cinderblock_core::resource) macro generates Axum
//! route handlers and endpoint registration code. At startup, all registered
//! endpoints are automatically discovered via [`inventory`] and assembled into
//! an [`axum::Router`].
//!
//! # Extension configuration
//!
//! Inside the `extensions` block of a [`resource!`](cinderblock_core::resource)
//! invocation, declare routes and optional settings:
//!
//! ```rust,ignore
//! extensions {
//!     cinderblock_json_api {
//!         // Each `route` maps an HTTP method + path to a resource action.
//!         route = { method = GET;    path = "/";              action = all;    };
//!         route = { method = POST;   path = "/";              action = open;   };
//!         route = { method = POST;   path = "/assign";        action = assign; };
//!         route = { method = PATCH;  path = "/{primary_key}"; action = close;  };
//!         route = { method = DELETE; path = "/{primary_key}"; action = remove; };
//!
//!         // Optional: override the auto-derived base path.
//!         // Default: kebab-case of resource name segments joined by `/`.
//!         //   e.g. `Helpdesk.Support.Ticket` -> `/helpdesk/support/ticket`
//!         // base_path = "/api/v1/tickets";
//!
//!         // Optional: disable OpenAPI spec generation. Default: true.
//!         // openapi = false;
//!     };
//! }
//! ```
//!
//! ## Route configuration
//!
//! | Field | Required | Description |
//! |---|---|---|
//! | `method` | yes | HTTP method: `GET`, `POST`, `PATCH`, `PUT`, or `DELETE` |
//! | `path` | yes | Path relative to the base path. Use `/{primary_key}` for routes that operate on a single resource. |
//! | `action` | yes | Name of a declared action on the resource. Must match the action kind (e.g. `GET` for `read`, `POST` for `create`). |
//!
//! The action name must refer to an action declared in the resource's `actions`
//! block. Duplicate method + path combinations are rejected at compile time.
//!
//! ## Route behavior by action kind
//!
//! - **Read** (`GET`): query parameters are deserialized into the action's
//!   `Arguments` struct. Returns `{ "data": [...] }`.
//! - **Create** (`POST`): JSON body is deserialized into the action's `Input`
//!   struct. Returns `{ "data": <resource> }`.
//! - **Update** (`PATCH`/`PUT`): primary key is extracted from the URL path,
//!   JSON body is deserialized into the action's `Input` struct. Returns
//!   `{ "data": <resource> }`.
//! - **Destroy** (`DELETE`): primary key is extracted from the URL path.
//!   Returns `{ "data": <resource> }` with the deleted resource.
//!
//! All responses are wrapped in a [`Response`] envelope (`{ "data": ... }`).
//!
//! ## OpenAPI and Swagger UI
//!
//! By default, the extension generates an OpenAPI spec fragment for each
//! resource. These fragments are merged and served at `GET /openapi.json`.
//!
//! When the `swagger-ui` feature is enabled, a Swagger UI is mounted at
//! `/swagger-ui`. This can be toggled off via [`RouterConfig::swagger_ui`].
//!
//! ## CORS
//!
//! When the `cors` feature is enabled, CORS middleware can be configured via
//! [`RouterConfig::cors`] or [`RouterConfig::cors_permissive`]:
//!
//! ```rust,ignore
//! use cinderblock_json_api::tower_http::cors::CorsLayer;
//! use http::{Method, header};
//!
//! // Production: explicit origins and methods.
//! let app = cinderblock_json_api::RouterConfig::new(ctx)
//!     .cors(CorsLayer::new()
//!         .allow_origin("https://app.example.com".parse::<http::HeaderValue>().unwrap())
//!         .allow_methods([Method::GET, Method::POST])
//!         .allow_headers([header::AUTHORIZATION, header::CONTENT_TYPE]))
//!     .build();
//!
//! // Development: allow everything.
//! let app = cinderblock_json_api::RouterConfig::new(ctx)
//!     .cors_permissive()
//!     .build();
//! ```
//!
//! ## Custom types in OpenAPI schemas
//!
//! The generated OpenAPI schemas use the [`FieldSchema`] trait to produce
//! schemas for each attribute type. Built-in types (`String`, integers, `bool`,
//! `Uuid`) have implementations provided. For custom types (like enums),
//! derive [`utoipa::ToSchema`] and bridge it with [`impl_field_schema!`]:
//!
//! ```rust,ignore
//! #[derive(Debug, Clone, Serialize, Deserialize, cinderblock_json_api::utoipa::ToSchema)]
//! enum TicketStatus {
//!     Open,
//!     Closed,
//! }
//!
//! cinderblock_json_api::impl_field_schema!(TicketStatus);
//! ```
//!
//! # Building the router
//!
//! Use [`router()`] for the common case, or [`RouterConfig`] for more control:
//!
//! ```rust,ignore
//! let ctx = cinderblock_core::Context::new();
//!
//! // Simple — all defaults.
//! let app = cinderblock_json_api::router(ctx);
//!
//! // Or configure options like Swagger UI.
//! let app = cinderblock_json_api::RouterConfig::new(ctx)
//!     .swagger_ui(false)
//!     .build();
//!
//! let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await?;
//! axum::serve(listener, app).await?;
//! ```
//!
//! # Full example
//!
//! ```rust,ignore
//! use cinderblock_core::{Context, resource, serde::{Deserialize, Serialize}};
//! use uuid::Uuid;
//!
//! resource! {
//!     name = Helpdesk.Support.Ticket;
//!
//!     attributes {
//!         ticket_id Uuid {
//!             primary_key true;
//!             writable false;
//!             default || Uuid::new_v4();
//!         }
//!         subject String;
//!         status TicketStatus;
//!     }
//!
//!     actions {
//!         read all {
//!             argument { status: Option<TicketStatus> };
//!             filter { status == arg(status) };
//!         };
//!         create open;
//!         update close {
//!             accept [];
//!             change_ref |ticket| { ticket.status = TicketStatus::Closed; };
//!         };
//!         destroy remove;
//!     }
//!
//!     extensions {
//!         cinderblock_json_api {
//!             route = { method = GET;    path = "/";              action = all;    };
//!             route = { method = POST;   path = "/";              action = open;   };
//!             route = { method = PATCH;  path = "/{primary_key}"; action = close;  };
//!             route = { method = DELETE; path = "/{primary_key}"; action = remove; };
//!         };
//!     }
//! }
//!
//! #[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq,
//!          cinderblock_json_api::utoipa::ToSchema)]
//! enum TicketStatus { #[default] Open, Closed }
//! cinderblock_json_api::impl_field_schema!(TicketStatus);
//!
//! #[tokio::main]
//! async fn main() -> cinderblock_core::Result<()> {
//!     let ctx = Context::new();
//!     let router = cinderblock_json_api::router(ctx);
//!     let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await?;
//!     axum::serve(listener, router).await?;
//!     Ok(())
//! }
//! ```

use std::sync::Arc;

pub use serde;

// Re-export dependencies for macro hygiene — the generated code from
// `cinderblock-json-api-macros` references these through `cinderblock_json_api::axum`,
// `cinderblock_json_api::tracing`, etc., so they must be available at the
// call site without the user adding them as direct dependencies.
pub use axum;
pub use inventory;
pub use tracing;
pub use utoipa;

// Re-export tower-http so users can build a `CorsLayer` without adding the
// dependency themselves.  Only available when the `cors` feature is enabled.
#[cfg(feature = "cors")]
pub use tower_http;

// Re-export the extension proc macro so `resource!` can call
// `cinderblock_json_api::__resource_extension!`.
pub use cinderblock_json_api_macros::__resource_extension;

/// Helper trait that provides OpenAPI schema generation for types used as
/// resource attribute fields.
///
/// This exists because `utoipa::PartialSchema` is a foreign trait, so we
/// can't impl it for foreign types like `uuid::Uuid` due to orphan rules.
/// The extension macro generates calls to
/// `<Type as cinderblock_json_api::FieldSchema>::field_schema()` instead of
/// `<Type as utoipa::PartialSchema>::schema()`.
///
/// Types that derive `utoipa::ToSchema` (which implies `PartialSchema`)
/// can use the blanket impl via the `partial_schema_field_schema!` macro.
/// Common built-in types (`String`, integers, `bool`, `Uuid`) have
/// explicit impls provided here.
pub trait FieldSchema {
    fn field_schema() -> utoipa::openapi::RefOr<utoipa::openapi::schema::Schema>;
}

/// Implements `FieldSchema` for types that already have `PartialSchema`.
///
/// Users call this for their own types that derive `ToSchema`:
/// ```rust,ignore
/// #[derive(utoipa::ToSchema)]
/// enum TicketStatus { Open, Closed }
/// cinderblock_json_api::impl_field_schema!(TicketStatus);
/// ```
#[macro_export]
macro_rules! impl_field_schema {
    ($ty:ty) => {
        impl $crate::FieldSchema for $ty {
            fn field_schema()
            -> $crate::utoipa::openapi::RefOr<$crate::utoipa::openapi::schema::Schema> {
                <$ty as $crate::utoipa::PartialSchema>::schema()
            }
        }
    };
}

// # Built-in FieldSchema implementations
//
// These cover the common Rust types that appear as resource attribute
// fields. The schemas match what utoipa's built-in `ComposeSchema` impls
// would produce.

macro_rules! impl_field_schema_string {
    ($($ty:ty),*) => {
        $(
            impl FieldSchema for $ty {
                fn field_schema() -> utoipa::openapi::RefOr<utoipa::openapi::schema::Schema> {
                    use utoipa::openapi::schema::{ObjectBuilder, SchemaType, Type};
                    ObjectBuilder::new()
                        .schema_type(SchemaType::new(Type::String))
                        .into()
                }
            }
        )*
    };
}

macro_rules! impl_field_schema_integer {
    ($($ty:ty => $format:expr),*) => {
        $(
            impl FieldSchema for $ty {
                fn field_schema() -> utoipa::openapi::RefOr<utoipa::openapi::schema::Schema> {
                    use utoipa::openapi::schema::{ObjectBuilder, SchemaType, SchemaFormat, Type};
                    ObjectBuilder::new()
                        .schema_type(SchemaType::new(Type::Integer))
                        .format(Some(SchemaFormat::KnownFormat($format)))
                        .into()
                }
            }
        )*
    };
}

macro_rules! impl_field_schema_number {
    ($($ty:ty => $format:expr),*) => {
        $(
            impl FieldSchema for $ty {
                fn field_schema() -> utoipa::openapi::RefOr<utoipa::openapi::schema::Schema> {
                    use utoipa::openapi::schema::{ObjectBuilder, SchemaType, SchemaFormat, Type};
                    ObjectBuilder::new()
                        .schema_type(SchemaType::new(Type::Number))
                        .format(Some(SchemaFormat::KnownFormat($format)))
                        .into()
                }
            }
        )*
    };
}

impl_field_schema_string!(String);

impl FieldSchema for bool {
    fn field_schema() -> utoipa::openapi::RefOr<utoipa::openapi::schema::Schema> {
        use utoipa::openapi::schema::{ObjectBuilder, SchemaType, Type};
        ObjectBuilder::new()
            .schema_type(SchemaType::new(Type::Boolean))
            .into()
    }
}

impl_field_schema_integer!(
    i8 => utoipa::openapi::KnownFormat::Int32,
    i16 => utoipa::openapi::KnownFormat::Int32,
    i32 => utoipa::openapi::KnownFormat::Int32,
    i64 => utoipa::openapi::KnownFormat::Int64,
    u8 => utoipa::openapi::KnownFormat::Int32,
    u16 => utoipa::openapi::KnownFormat::Int32,
    u32 => utoipa::openapi::KnownFormat::Int32,
    u64 => utoipa::openapi::KnownFormat::Int64,
    isize => utoipa::openapi::KnownFormat::Int64,
    usize => utoipa::openapi::KnownFormat::Int64
);

impl_field_schema_number!(
    f32 => utoipa::openapi::KnownFormat::Float,
    f64 => utoipa::openapi::KnownFormat::Double
);

impl FieldSchema for uuid::Uuid {
    fn field_schema() -> utoipa::openapi::RefOr<utoipa::openapi::schema::Schema> {
        use utoipa::openapi::schema::{ObjectBuilder, SchemaFormat, SchemaType, Type};
        ObjectBuilder::new()
            .schema_type(SchemaType::new(Type::String))
            .format(Some(SchemaFormat::KnownFormat(
                utoipa::openapi::KnownFormat::Uuid,
            )))
            .into()
    }
}

impl<T: FieldSchema> FieldSchema for Option<T> {
    fn field_schema() -> utoipa::openapi::RefOr<utoipa::openapi::schema::Schema> {
        use utoipa::openapi::schema::{Schema, SchemaType, Type};

        let inner = T::field_schema();

        match inner {
            utoipa::openapi::RefOr::T(Schema::Object(mut obj)) => {
                // Add `Type::Null` to make the schema nullable in OpenAPI 3.1
                let nullable_type = match obj.schema_type {
                    SchemaType::Type(t) => SchemaType::Array(vec![t, Type::Null]),
                    SchemaType::Array(mut types) => {
                        types.push(Type::Null);
                        SchemaType::Array(types)
                    }
                    SchemaType::AnyValue => SchemaType::AnyValue,
                };
                obj.schema_type = nullable_type;
                obj.into()
            }
            other => other,
        }
    }
}

/// Generic JSON API response envelope.
///
/// Wraps all responses in a `{ "data": ... }` structure so the format is
/// extensible with future fields like pagination, links, or errors.
///
/// For list endpoints `T` is `Vec<R>`, for single-resource endpoints it
/// will be `R` directly.
#[derive(Debug, serde::Serialize)]
pub struct Response<T: serde::Serialize> {
    pub data: T,
}

/// JSON API response envelope for paginated list endpoints.
///
/// Returns `{ "data": [...], "meta": { page, per_page, total, total_pages } }`.
/// Used by paged read action handlers instead of the plain [`Response`] envelope.
#[derive(Debug, serde::Serialize)]
pub struct PaginatedResponse<T: serde::Serialize> {
    pub data: Vec<T>,
    pub meta: PaginationMeta,
}

/// Pagination metadata included in [`PaginatedResponse`].
#[derive(Debug, serde::Serialize)]
pub struct PaginationMeta {
    pub page: u32,
    pub per_page: u32,
    pub total: u64,
    pub total_pages: u32,
}

// # PartialSchema / ToSchema for Response<T>
//
// Manual implementations so the generated OpenAPI spec can describe the
// `{ "data": ... }` envelope without requiring a derive on a struct that
// has a generic type parameter. The schema delegates to `T`'s schema for
// the `data` property.
impl<T> utoipa::PartialSchema for Response<T>
where
    T: serde::Serialize + utoipa::PartialSchema,
{
    fn schema() -> utoipa::openapi::RefOr<utoipa::openapi::schema::Schema> {
        use utoipa::openapi::schema::{ObjectBuilder, SchemaType, Type};

        ObjectBuilder::new()
            .schema_type(SchemaType::new(Type::Object))
            .property("data", T::schema())
            .required("data")
            .into()
    }
}

impl<T> utoipa::ToSchema for Response<T>
where
    T: serde::Serialize + utoipa::PartialSchema,
{
    fn name() -> std::borrow::Cow<'static, str> {
        std::borrow::Cow::Borrowed("Response")
    }
}

// # PartialSchema / ToSchema for PaginatedResponse<T>
//
// Describes the `{ "data": [...], "meta": {...} }` shape for OpenAPI specs.
impl<T> utoipa::PartialSchema for PaginatedResponse<T>
where
    T: serde::Serialize + utoipa::PartialSchema,
{
    fn schema() -> utoipa::openapi::RefOr<utoipa::openapi::schema::Schema> {
        use utoipa::openapi::schema::{
            ArrayBuilder, ObjectBuilder, SchemaFormat, SchemaType, Type,
        };

        let meta_schema = ObjectBuilder::new()
            .schema_type(SchemaType::new(Type::Object))
            .property(
                "page",
                ObjectBuilder::new()
                    .schema_type(SchemaType::new(Type::Integer))
                    .format(Some(SchemaFormat::KnownFormat(
                        utoipa::openapi::KnownFormat::Int32,
                    ))),
            )
            .required("page")
            .property(
                "per_page",
                ObjectBuilder::new()
                    .schema_type(SchemaType::new(Type::Integer))
                    .format(Some(SchemaFormat::KnownFormat(
                        utoipa::openapi::KnownFormat::Int32,
                    ))),
            )
            .required("per_page")
            .property(
                "total",
                ObjectBuilder::new()
                    .schema_type(SchemaType::new(Type::Integer))
                    .format(Some(SchemaFormat::KnownFormat(
                        utoipa::openapi::KnownFormat::Int64,
                    ))),
            )
            .required("total")
            .property(
                "total_pages",
                ObjectBuilder::new()
                    .schema_type(SchemaType::new(Type::Integer))
                    .format(Some(SchemaFormat::KnownFormat(
                        utoipa::openapi::KnownFormat::Int32,
                    ))),
            )
            .required("total_pages");

        ObjectBuilder::new()
            .schema_type(SchemaType::new(Type::Object))
            .property("data", ArrayBuilder::new().items(T::schema()))
            .required("data")
            .property("meta", meta_schema)
            .required("meta")
            .into()
    }
}

impl<T> utoipa::ToSchema for PaginatedResponse<T>
where
    T: serde::Serialize + utoipa::PartialSchema,
{
    fn name() -> std::borrow::Cow<'static, str> {
        std::borrow::Cow::Borrowed("PaginatedResponse")
    }
}

/// A registered resource endpoint. Extension macros generate instances of this
/// struct and submit them via `inventory::submit!`. The `register` function
/// takes an existing router and context, and returns a new router with the
/// resource's endpoints added.
///
/// The optional `openapi` function returns an OpenAPI spec fragment for the
/// resource's endpoints. When present, the router builder merges all fragments
/// into a single spec served at `/openapi.json`.
pub struct ResourceEndpoint {
    pub register: fn(axum::Router, Arc<cinderblock_core::Context>) -> axum::Router,
    pub openapi: Option<fn() -> utoipa::openapi::OpenApi>,
}

inventory::collect!(ResourceEndpoint);

/// Configuration builder for the JSON API router.
///
/// Allows controlling optional features like Swagger UI before building
/// the final `axum::Router`.
///
/// ```rust,ignore
/// let router = cinderblock_json_api::RouterConfig::new(ctx)
///     .swagger_ui(true)
///     .build();
/// ```
pub struct RouterConfig {
    ctx: Arc<cinderblock_core::Context>,
    swagger_ui: bool,
    #[cfg(feature = "cors")]
    cors: Option<tower_http::cors::CorsLayer>,
}

impl RouterConfig {
    pub fn new(ctx: impl Into<Arc<cinderblock_core::Context>>) -> Self {
        Self {
            ctx: ctx.into(),
            swagger_ui: true,
            #[cfg(feature = "cors")]
            cors: None,
        }
    }

    /// Enable or disable the Swagger UI endpoint at `/swagger-ui`.
    /// Only takes effect when the `utoipa-swagger-ui` feature is enabled.
    /// Default: `true`.
    pub fn swagger_ui(mut self, enabled: bool) -> Self {
        self.swagger_ui = enabled;
        self
    }

    /// Set a custom CORS layer.
    /// Only takes effect when the `cors` feature is enabled.
    #[cfg(feature = "cors")]
    pub fn cors(mut self, layer: tower_http::cors::CorsLayer) -> Self {
        self.cors = Some(layer);
        self
    }

    /// Enable a permissive CORS policy (allow any origin, method, and header).
    /// Intended for local development only.
    /// Only takes effect when the `cors` feature is enabled.
    #[cfg(feature = "cors")]
    pub fn cors_permissive(mut self) -> Self {
        self.cors = Some(tower_http::cors::CorsLayer::permissive());
        self
    }

    pub fn build(self) -> axum::Router {
        let mut router = axum::Router::new();

        // # Endpoint registration + OpenAPI spec collection
        //
        // Each resource that declared `cinderblock_json_api` in its extensions block
        // contributes both route handlers and an optional OpenAPI spec
        // fragment. We collect the fragments and merge them afterward.
        let mut openapi_specs: Vec<utoipa::openapi::OpenApi> = Vec::new();

        for endpoint in inventory::iter::<ResourceEndpoint> {
            router = (endpoint.register)(router, self.ctx.clone());

            if let Some(openapi_fn) = endpoint.openapi {
                openapi_specs.push(openapi_fn());
            }
        }

        // # OpenAPI spec merging
        //
        // Build a base spec and merge each resource's fragment into it.
        // The merged spec is served at GET /openapi.json.
        if !openapi_specs.is_empty() {
            let mut merged = utoipa::openapi::OpenApiBuilder::new()
                .info(
                    utoipa::openapi::InfoBuilder::new()
                        .title("Cinderblock JSON API")
                        .version("0.1.0")
                        .build(),
                )
                .build();

            for spec in openapi_specs {
                merged.merge(spec);
            }

            // # Swagger UI
            //
            // When the `swagger-ui` feature is enabled and the user hasn't
            // disabled it, mount the Swagger UI at `/swagger-ui`. The
            // SwaggerUi widget also serves the spec at `/openapi.json`.
            #[cfg(feature = "swagger-ui")]
            if self.swagger_ui {
                router = router.merge(
                    utoipa_swagger_ui::SwaggerUi::new("/swagger-ui").url("/openapi.json", merged),
                );
            }

            #[cfg(not(feature = "swagger-ui"))]
            let _ = self.swagger_ui;
        }

        #[cfg(feature = "cors")]
        if let Some(cors_layer) = self.cors {
            router = router.layer(cors_layer);
        }

        router
    }
}

/// Builds an `axum::Router` containing all auto-registered JSON API endpoints.
///
/// This is a convenience wrapper around `RouterConfig::new(ctx).build()`.
/// Each resource that declared `cinderblock_json_api` in its `extensions` block will
/// have its endpoints automatically included via `inventory` — no manual
/// route construction is needed.
pub fn router(ctx: impl Into<Arc<cinderblock_core::Context>>) -> axum::Router {
    RouterConfig::new(ctx).build()
}