entity-derive-impl 0.3.0

Internal proc-macro implementation for entity-derive. Use entity-derive instead.
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
// SPDX-FileCopyrightText: 2025-2026 RAprogramm <andrey.rozanov.vl@gmail.com>
// SPDX-License-Identifier: MIT

//! Helper functions for CRUD handler generation.
//!
//! This module provides utility functions used across all CRUD handler
//! generators. These helpers handle common tasks like URL path construction
//! and security attribute generation.
//!
//! # Overview
//!
//! The helpers in this module are responsible for:
//!
//! - **Path Building**: Constructing RESTful URL paths following conventions
//! - **Security Attributes**: Generating utoipa security annotations
//! - **Deprecation Handling**: Adding deprecated markers to OpenAPI spec
//!
//! # Path Conventions
//!
//! All paths follow REST conventions:
//!
//! | Resource Type | Pattern | Example |
//! |---------------|---------|---------|
//! | Collection | `/{prefix}/{entity}s` | `/api/v1/users` |
//! | Item | `/{prefix}/{entity}s/{id}` | `/api/v1/users/{id}` |
//!
//! Entity names are converted to kebab-case and pluralized.
//!
//! # Security Schemes
//!
//! Supported authentication schemes:
//!
//! | Scheme | OpenAPI Name | Description |
//! |--------|--------------|-------------|
//! | `cookie` | `cookieAuth` | JWT in HTTP-only cookie |
//! | `bearer` | `bearerAuth` | JWT in Authorization header |
//! | `api_key` | `apiKey` | API key in X-API-Key header |
//!
//! # Example
//!
//! ```rust,ignore
//! use crate::entity::api::crud::helpers::*;
//!
//! // For entity "UserProfile" with prefix "/api/v1":
//! let collection = build_collection_path(&entity);
//! // Result: "/api/v1/user-profiles"
//!
//! let item = build_item_path(&entity);
//! // Result: "/api/v1/user-profiles/{id}"
//! ```

use convert_case::{Case, Casing};
use proc_macro2::TokenStream;
use quote::quote;

use crate::entity::parse::EntityDef;

/// Builds the collection endpoint path for an entity.
///
/// Constructs the URL path for collection-level operations (list, create).
/// The path follows REST conventions: `/{prefix}/{entity}s`.
///
/// # Path Construction
///
/// The path is built from three components:
///
/// 1. **Prefix**: From `api(path_prefix = "...")` attribute
/// 2. **Entity name**: Converted to kebab-case
/// 3. **Plural suffix**: Always adds "s" for collections
///
/// # Arguments
///
/// * `entity` - The parsed entity definition containing API configuration
///
/// # Returns
///
/// A `String` containing the full collection path.
///
/// # Examples
///
/// ```rust,ignore
/// // Entity: User, prefix: /api/v1
/// build_collection_path(&entity) // "/api/v1/users"
///
/// // Entity: UserProfile, prefix: /api
/// build_collection_path(&entity) // "/api/user-profiles"
///
/// // Entity: Order, no prefix
/// build_collection_path(&entity) // "/orders"
/// ```
///
/// # Notes
///
/// - Double slashes (`//`) are automatically normalized to single slashes
/// - Entity names are converted from PascalCase to kebab-case
/// - The plural form is naive (just adds "s"), not grammatically correct
pub fn build_collection_path(entity: &EntityDef) -> String {
    let api_config = entity.api_config();
    let prefix = api_config.full_path_prefix();
    let entity_path = entity.name_str().to_case(Case::Kebab);

    let path = format!("{}/{}s", prefix, entity_path);
    path.replace("//", "/")
}

/// Builds the item endpoint path for an entity.
///
/// Constructs the URL path for item-level operations (get, update, delete).
/// The path follows REST conventions: `/{prefix}/{entity}s/{id}`.
///
/// # Path Construction
///
/// Extends the collection path with an `{id}` path parameter:
///
/// ```text
/// /api/v1/users/{id}
///        ↑       ↑
///   collection  parameter
/// ```
///
/// # Arguments
///
/// * `entity` - The parsed entity definition containing API configuration
///
/// # Returns
///
/// A `String` containing the full item path with `{id}` placeholder.
///
/// # Examples
///
/// ```rust,ignore
/// // Entity: User, prefix: /api/v1
/// build_item_path(&entity) // "/api/v1/users/{id}"
///
/// // Entity: BlogPost, no prefix
/// build_item_path(&entity) // "/blog-posts/{id}"
/// ```
///
/// # OpenAPI Integration
///
/// The `{id}` placeholder is recognized by utoipa and generates:
///
/// ```yaml
/// parameters:
///   - name: id
///     in: path
///     required: true
/// ```
pub fn build_item_path(entity: &EntityDef) -> String {
    let collection = build_collection_path(entity);
    format!("{}/{{id}}", collection)
}

/// Generates the utoipa security attribute for a handler.
///
/// Creates the `security((...))` attribute used in `#[utoipa::path]`
/// annotations. The security scheme is determined by the entity's
/// API configuration.
///
/// # Security Scheme Mapping
///
/// | Config Value | OpenAPI Scheme | Authentication Method |
/// |--------------|----------------|----------------------|
/// | `"cookie"` | `cookieAuth` | JWT in HTTP-only cookie |
/// | `"bearer"` | `bearerAuth` | JWT in Authorization header |
/// | `"api_key"` | `apiKey` | Key in X-API-Key header |
/// | Other | `cookieAuth` | Falls back to cookie auth |
///
/// # Arguments
///
/// * `entity` - The parsed entity definition containing security config
///
/// # Returns
///
/// A `TokenStream` containing either:
/// - `security(("schemeName" = []))` if security is configured
/// - Empty `TokenStream` if no security is configured
///
/// # Generated Code Examples
///
/// With `security = "bearer"`:
/// ```rust,ignore
/// #[utoipa::path(
///     // ...
///     security(("bearerAuth" = []))
/// )]
/// ```
///
/// With `security = "cookie"`:
/// ```rust,ignore
/// #[utoipa::path(
///     // ...
///     security(("cookieAuth" = []))
/// )]
/// ```
///
/// Without security:
/// ```rust,ignore
/// #[utoipa::path(
///     // ... (no security attribute)
/// )]
/// ```
///
/// # OpenAPI Spec
///
/// The generated security requirement references a security scheme
/// that must be defined in the OpenAPI components. See
/// [`crate::entity::api::openapi::security`] for scheme definitions.
pub fn build_security_attr(entity: &EntityDef) -> TokenStream {
    let api_config = entity.api_config();

    if let Some(security) = &api_config.security {
        let security_name = match security.as_str() {
            "cookie" => "cookieAuth",
            "bearer" => "bearerAuth",
            "api_key" => "apiKey",
            _ => "cookieAuth"
        };
        quote! { security((#security_name = [])) }
    } else {
        TokenStream::new()
    }
}

/// Generates the deprecated attribute for API endpoints.
///
/// Creates the `deprecated = true` attribute used in `#[utoipa::path]`
/// annotations when the entity's API is marked as deprecated.
///
/// # Deprecation Flow
///
/// 1. Entity marked with `api(deprecated_in = "v2")`
/// 2. This function returns `deprecated = true` attribute
/// 3. OpenAPI spec shows endpoint as deprecated
/// 4. Swagger UI displays strikethrough on deprecated endpoints
///
/// # Arguments
///
/// * `entity` - The parsed entity definition containing deprecation info
///
/// # Returns
///
/// A `TokenStream` containing either:
/// - `, deprecated = true` if API is deprecated
/// - Empty `TokenStream` if API is not deprecated
///
/// # Generated Code Examples
///
/// With `api(deprecated_in = "v2")`:
/// ```rust,ignore
/// #[utoipa::path(
///     get,
///     path = "/users/{id}",
///     // ...
///     , deprecated = true  // ← generated by this function
/// )]
/// ```
///
/// Without deprecation:
/// ```rust,ignore
/// #[utoipa::path(
///     get,
///     path = "/users/{id}",
///     // ... (no deprecated attribute)
/// )]
/// ```
///
/// # Visual Result
///
/// In Swagger UI, deprecated endpoints appear with:
/// - Strikethrough text on the endpoint name
/// - "Deprecated" badge
/// - Grayed out styling
pub fn build_deprecated_attr(entity: &EntityDef) -> TokenStream {
    if entity.api_config().is_deprecated() {
        quote! { , deprecated = true }
    } else {
        TokenStream::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn collection_path_simple() {
        let input: syn::DeriveInput = syn::parse_quote! {
            #[entity(table = "users", api(tag = "Users", handlers))]
            pub struct User {
                #[id]
                pub id: uuid::Uuid,
            }
        };
        let entity = EntityDef::from_derive_input(&input).unwrap();
        let path = build_collection_path(&entity);
        assert_eq!(path, "/users");
    }

    #[test]
    fn collection_path_with_prefix() {
        let input: syn::DeriveInput = syn::parse_quote! {
            #[entity(table = "users", api(tag = "Users", path_prefix = "/api/v1", handlers))]
            pub struct User {
                #[id]
                pub id: uuid::Uuid,
            }
        };
        let entity = EntityDef::from_derive_input(&input).unwrap();
        let path = build_collection_path(&entity);
        assert_eq!(path, "/api/v1/users");
    }

    #[test]
    fn collection_path_kebab_case() {
        let input: syn::DeriveInput = syn::parse_quote! {
            #[entity(table = "user_profiles", api(tag = "UserProfiles", handlers))]
            pub struct UserProfile {
                #[id]
                pub id: uuid::Uuid,
            }
        };
        let entity = EntityDef::from_derive_input(&input).unwrap();
        let path = build_collection_path(&entity);
        assert_eq!(path, "/user-profiles");
    }

    #[test]
    fn item_path_simple() {
        let input: syn::DeriveInput = syn::parse_quote! {
            #[entity(table = "users", api(tag = "Users", handlers))]
            pub struct User {
                #[id]
                pub id: uuid::Uuid,
            }
        };
        let entity = EntityDef::from_derive_input(&input).unwrap();
        let path = build_item_path(&entity);
        assert_eq!(path, "/users/{id}");
    }

    #[test]
    fn item_path_with_prefix() {
        let input: syn::DeriveInput = syn::parse_quote! {
            #[entity(table = "users", api(tag = "Users", path_prefix = "/api/v2", handlers))]
            pub struct User {
                #[id]
                pub id: uuid::Uuid,
            }
        };
        let entity = EntityDef::from_derive_input(&input).unwrap();
        let path = build_item_path(&entity);
        assert_eq!(path, "/api/v2/users/{id}");
    }

    #[test]
    fn security_attr_bearer() {
        let input: syn::DeriveInput = syn::parse_quote! {
            #[entity(table = "users", api(tag = "Users", security = "bearer", handlers))]
            pub struct User {
                #[id]
                pub id: uuid::Uuid,
            }
        };
        let entity = EntityDef::from_derive_input(&input).unwrap();
        let attr = build_security_attr(&entity);
        let attr_str = attr.to_string();
        assert!(attr_str.contains("bearerAuth"));
    }

    #[test]
    fn security_attr_cookie() {
        let input: syn::DeriveInput = syn::parse_quote! {
            #[entity(table = "users", api(tag = "Users", security = "cookie", handlers))]
            pub struct User {
                #[id]
                pub id: uuid::Uuid,
            }
        };
        let entity = EntityDef::from_derive_input(&input).unwrap();
        let attr = build_security_attr(&entity);
        let attr_str = attr.to_string();
        assert!(attr_str.contains("cookieAuth"));
    }

    #[test]
    fn security_attr_api_key() {
        let input: syn::DeriveInput = syn::parse_quote! {
            #[entity(table = "users", api(tag = "Users", security = "api_key", handlers))]
            pub struct User {
                #[id]
                pub id: uuid::Uuid,
            }
        };
        let entity = EntityDef::from_derive_input(&input).unwrap();
        let attr = build_security_attr(&entity);
        let attr_str = attr.to_string();
        assert!(attr_str.contains("apiKey"));
    }

    #[test]
    fn security_attr_unknown_defaults_to_cookie() {
        let input: syn::DeriveInput = syn::parse_quote! {
            #[entity(table = "users", api(tag = "Users", security = "custom", handlers))]
            pub struct User {
                #[id]
                pub id: uuid::Uuid,
            }
        };
        let entity = EntityDef::from_derive_input(&input).unwrap();
        let attr = build_security_attr(&entity);
        let attr_str = attr.to_string();
        assert!(attr_str.contains("cookieAuth"));
    }

    #[test]
    fn security_attr_none() {
        let input: syn::DeriveInput = syn::parse_quote! {
            #[entity(table = "users", api(tag = "Users", handlers))]
            pub struct User {
                #[id]
                pub id: uuid::Uuid,
            }
        };
        let entity = EntityDef::from_derive_input(&input).unwrap();
        let attr = build_security_attr(&entity);
        assert!(attr.is_empty());
    }

    #[test]
    fn deprecated_attr_present() {
        let input: syn::DeriveInput = syn::parse_quote! {
            #[entity(table = "users", api(tag = "Users", deprecated_in = "2.0", handlers))]
            pub struct User {
                #[id]
                pub id: uuid::Uuid,
            }
        };
        let entity = EntityDef::from_derive_input(&input).unwrap();
        let attr = build_deprecated_attr(&entity);
        let attr_str = attr.to_string();
        assert!(attr_str.contains("deprecated = true"));
    }

    #[test]
    fn deprecated_attr_absent() {
        let input: syn::DeriveInput = syn::parse_quote! {
            #[entity(table = "users", api(tag = "Users", handlers))]
            pub struct User {
                #[id]
                pub id: uuid::Uuid,
            }
        };
        let entity = EntityDef::from_derive_input(&input).unwrap();
        let attr = build_deprecated_attr(&entity);
        assert!(attr.is_empty());
    }
}