| Crates.io | reinhardt-macros |
| lib.rs | reinhardt-macros |
| version | 0.1.0-alpha.1 |
| created_at | 2026-01-22 17:03:46.4912+00 |
| updated_at | 2026-01-22 17:03:46.4912+00 |
| description | Procedural macros for Reinhardt framework |
| homepage | |
| repository | https://github.com/kent8192/reinhardt-rs |
| max_upload_size | |
| id | 2062201 |
| size | 457,514 |
Procedural macros for the framework
Procedural macros for reducing boilerplate code. Includes derive macros for models, serializers, and forms, as well as attribute macros for endpoints and middleware.
Provides compile-time code generation for common patterns.
#[api_view] - Convert function to API view
methods parameter#[api_view(methods = "GET,POST")]#[action] - Define custom ViewSet actions
methods parameterdetail parameter (required)url_path and url_name parameters#[action(methods = "POST", detail = true)]#[get] - GET method decorator with path validation#[post] - POST method decorator with path validation#[put] - PUT method decorator with path validation#[patch] - PATCH method decorator with path validation#[delete] - DELETE method decorator with path validationuse_inject = true option with #[inject] parameter attribute{id} or typed {<uuid:id>}, {<int:id>}, {<str:name>}, {<slug:title>}, {<path:route>}#[get("/users/{id}")]#[get("/users/{<uuid:id>}", use_inject = true)]#[permission_required] - Permission decorator
"app.permission"#[permission_required("users.view_user")]#[injectable] - Transform functions or structs into Injectable trait implementations
Function Usage: Factory functions for creating dependencies
#[inject]#[inject(cache = false)]#[inject(scope = Singleton)] or #[inject(scope = Request)]use reinhardt::di::injectable;
use std::sync::Arc;
#[injectable]
fn create_user_service(
#[inject] db: Arc<Database>,
#[inject] cache: Arc<Cache>,
) -> UserService {
UserService { db, cache }
}
Struct Usage: Auto-generate Injectable implementation
#[inject] or #[no_inject] attribute#[inject] - Inject from DI container (cached by default)#[inject(cache = false)] - Inject without caching#[inject(scope = Singleton)] - Use singleton scope#[no_inject(default = Default)] - Initialize with Default::default()#[no_inject(default = value)] - Initialize with specific value#[no_inject] - Initialize with None (field must be Option<T>)Clone (required by Injectable trait)use reinhardt::di::injectable;
#[injectable]
#[derive(Clone)]
struct UserViewSet {
#[inject]
db: Database,
#[inject]
cache: RedisCache,
#[no_inject(default = Default)]
config: Config,
}
#[get("/path", use_inject = true)] - GET with DI enabled#[post("/path", use_inject = true)] - POST with DI enabled#[put("/path", use_inject = true)] - PUT with DI enabled#[patch("/path", use_inject = true)] - PATCH with DI enabled#[delete("/path", use_inject = true)] - DELETE with DI enabled
#[inject]InjectionContextuse_inject = true is required when using #[inject] parametersuse reinhardt::views::{get, post};
use reinhardt::http::{Response, ViewResult};
use reinhardt::extractors::{Path, Json};
use std::sync::Arc;
use uuid::Uuid;
#[get("/users/{<uuid:id>}", use_inject = true)]
async fn get_user(
Path(id): Path<Uuid>,
#[inject] db: Arc<DatabaseConnection>, // Injected from context
) -> ViewResult<Response> {
// ...
}
#[post("/users", use_inject = true)]
async fn create_user(
Json(data): Json<CreateUserRequest>,
#[inject] db: Arc<DatabaseConnection>,
) -> ViewResult<Response> {
// ...
}
Pattern Comparison:
#[injectable] - Creates an Injectable implementation for the return type (Factory/Provider pattern)#[<http_method>(..., use_inject = true)] - Injects dependencies into function parametersinstalled_apps! - Define installed applications
reinhardt.* module paths at compile timeDisplay and FromStr implementationsinstalled_apps! { polls: "polls", } (user apps only)installed_apps!path! - Validate URL patterns at compile time
{id}{<int:id>}int, str, uuid, slug, pathpath!("users/{<int:user_id>}/posts/{post_id}/")#[receiver] - Connect receiver function to signal
@receiver decorator functionality#[receiver(signal = post_save::<User>())]#[derive(QueryFields)] - Generate field accessor methods
lower(), upper(), trim(), contains()abs(), ceil(), floor(), round()year(), month(), day(), hour()eq(), ne(), gt(), gte(), lt(), lte()QuerySet::<User>::new().filter(User::email().lower().contains("example.com"))#[model(...)] - Attribute macro for Django-style model definition
#[derive(Model)]#[derive(Model)]#[derive(Model)]#[model(table_name = "users", app_label = "auth")]#[derive(Model)] - Derive macro for automatic Model implementation
Model traitapp_label, table_name, constraintsprimary_key, max_length, null, blank, unique, default, db_column, editablei32, i64, String, bool, DateTime<Utc>, Date, Time, f32, f64, Option<T>Serialize/Deserialize, exactly one primary_key, max_length for String fields#[derive(OrmReflectable)] - Automatic OrmReflectable implementation
Vec<T> → collection, Option<T> → scalar, primitives → fields#[orm_field(type = "Integer")], #[orm_relationship(type = "collection")], #[orm_ignore]#[derive(Schema)] - Automatic OpenAPI 3.0 schema generation
ToSchema traitOption<T>, Vec<T>, custom types#[derive(AppConfig)] - AppConfig factory method generation
config() method returning AppConfigname (required), label (required), verbose_name (optional)#[derive(AppConfig)] #[app_config(name = "auth", label = "auth")]#[admin(...)] - ModelAdmin configuration with compile-time validation
ModelAdmin traitfor = ModelType, name = "ModelName"list_display, list_filter, search_fields, fields, readonly_fields, ordering, list_per_page#[admin(for = User, name = "User", list_display = [id, email, username])]#[routes] - Attribute macro for automatic URL pattern registration
inventory crate)routes() function in src/config/urls.rsUnifiedRouter (framework handles Arc wrapping internally)use reinhardt::prelude::*;
use reinhardt::routes;
#[routes]
pub fn routes() -> UnifiedRouter {
UnifiedRouter::new()
.mount("/api/", api_router())
}
collect_migrations! - Migration registration with global registry
MigrationProvider implementationlinkme::distributed_slicemigration() function#[use_inject] - Standalone dependency injection for any function
#[inject] parameters#[inject] parameters from signatureInjectionContext parameterAdd reinhardt to your Cargo.toml:
[dependencies]
reinhardt = { version = "0.1.0-alpha.1", features = ["core"] }
# Or use a preset:
# reinhardt = { version = "0.1.0-alpha.1", features = ["standard"] } # Recommended
# reinhardt = { version = "0.1.0-alpha.1", features = ["full"] } # All features
Note: The core feature (included in standard and full) is required to use the macros from this crate.