3.1 KiB
3.1 KiB
Hero Models
A Rust library for model management with a base model trait implementation and builder pattern support.
Features
- Base Model Trait: Common interface for all models with standard methods
- Builder Pattern: All models use the builder pattern for flexible and clear construction
- Indexing Support: Built-in support for model indexing with customizable keys
- Comment System: Integrated comment system that can be attached to any model
- Timestamps: Automatic creation and modification timestamps
Usage
Add this to your Cargo.toml
:
[dependencies]
heromodels = "0.1.0"
Basic Example
use heromodels::{BaseModel, User, Comment};
fn main() {
// Create a new user using the builder pattern
let user_result = User::builder(1)
.username("johndoe")
.email("john.doe@example.com")
.full_name("John Doe")
.build();
let mut user = user_result.expect("Failed to build user");
// Create a comment for the user using the builder pattern
let comment_result = Comment::builder(1)
.user_id(2) // commenter's user ID
.model_id(user.get_id())
.model_type(User::db_prefix())
.content("This is a comment on the user")
.build();
let comment = comment_result.expect("Failed to build comment");
// Add the comment to the user
user.base_data.add_comment(comment.get_id());
// Get the database keys for the user
let keys = user.db_keys();
for key in keys {
println!("{}: {}", key.name, key.value);
}
}
Creating Custom Models
To create your own model that inherits from the base model:
use serde::{Deserialize, Serialize};
use heromodels::model::{BaseModel, BaseModelData, IndexKey};
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Product {
pub base_data: BaseModelData,
pub name: String,
pub price: f64,
pub sku: String,
}
impl BaseModel for Product {
fn db_prefix() -> &'static str {
"product"
}
fn get_id(&self) -> u32 {
self.base_data.id
}
fn db_keys(&self) -> Vec<IndexKey> {
vec![
IndexKey {
name: "name",
value: self.name.clone(),
},
IndexKey {
name: "sku",
value: self.sku.clone(),
},
]
}
}
// Implement a builder for your custom model
pub struct ProductBuilder {
id: u32,
base_data_builder: Option<heromodels::model::BaseModelDataBuilder>,
name: Option<String>,
price: Option<f64>,
sku: Option<String>,
}
impl ProductBuilder {
pub fn new(id: u32) -> Self {
Self {
id,
base_data_builder: Some(BaseModelData::builder(id)),
name: None,
price: None,
sku: None,
}
}
// Add builder methods...
pub fn build(self) -> Result<Product, &'static str> {
// Implementation...
}
}
impl Product {
pub fn builder(id: u32) -> ProductBuilder {
ProductBuilder::new(id)
}
}
License
MIT