Skip to content
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
28 changes: 28 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ version = "0.0.1"
[workspace.dependencies]
fortifier = { path = "./packages/fortifier", version = "0.0.1" }
fortifier-macros = { path = "./packages/fortifier-macros", version = "0.0.1" }
tokio = "1.48.0"

[workspace.lints.rust]
unsafe_code = "deny"
Expand Down
1 change: 1 addition & 0 deletions example/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ version.workspace = true

[dependencies]
fortifier.workspace = true
tokio = { workspace = true, features = ["macros", "rt-multi-thread"] }

[lints]
workspace = true
20 changes: 18 additions & 2 deletions example/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,16 +12,32 @@ struct CreateUser {

#[validate(url)]
url: String,

#[validate(custom(function = validate_one_locale_required, error = OneLocaleRequiredError))]
locales: Vec<String>,
}

#[derive(Debug)]
struct OneLocaleRequiredError;

fn validate_one_locale_required(locales: &[String]) -> Result<(), OneLocaleRequiredError> {
if locales.is_empty() {
Err(OneLocaleRequiredError)
} else {
Ok(())
}
}

fn main() -> Result<(), Box<dyn Error>> {
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
let data = CreateUser {
email: "john@doe.com".to_owned(),
name: "John Doe".to_owned(),
url: "https://john.doe.com".to_owned(),
locales: vec!["en_GB".to_owned()],
};

data.validate_sync()?;
data.validate().await?;

Ok(())
}
8 changes: 6 additions & 2 deletions packages/fortifier-macros/src/validate/field.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use syn::{Field, Result};

use crate::{
validation::Validation,
validations::{Email, Length, Url},
validations::{Custom, Email, Length, Url},
};

pub struct ValidateField {
Expand All @@ -22,7 +22,11 @@ impl ValidateField {
for attr in &field.attrs {
if attr.path().is_ident("validate") {
attr.parse_nested_meta(|meta| {
if meta.path.is_ident("email") {
if meta.path.is_ident("custom") {
result.validations.push(Box::new(Custom::parse(&meta)?));

Ok(())
} else if meta.path.is_ident("email") {
result.validations.push(Box::new(Email::parse(&meta)?));

Ok(())
Expand Down
2 changes: 2 additions & 0 deletions packages/fortifier-macros/src/validations.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
mod custom;
mod email;
mod length;
mod url;

pub use custom::*;
pub use email::*;
pub use length::*;
pub use url::*;
77 changes: 77 additions & 0 deletions packages/fortifier-macros/src/validations/custom.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
use proc_macro2::TokenStream;
use quote::{ToTokens, quote};
use syn::{LitBool, Path, Result, Type, meta::ParseNestedMeta};

use crate::validation::Validation;

pub struct Custom {
is_async: bool,
error_type: Type,
function_path: Path,
}

impl Validation for Custom {
fn parse(meta: &ParseNestedMeta<'_>) -> Result<Self> {
let mut is_async = false;
let mut error_type: Option<Type> = None;
let mut function_path: Option<Path> = None;

meta.parse_nested_meta(|meta| {
if meta.path.is_ident("async") {
if let Ok(value) = meta.value() {
let lit: LitBool = value.parse()?;
is_async = lit.value;
} else {
is_async = true;
}

Ok(())
} else if meta.path.is_ident("error") {
error_type = Some(meta.value()?.parse()?);

Ok(())
} else if meta.path.is_ident("function") {
function_path = Some(meta.value()?.parse()?);

Ok(())
} else {
Err(meta.error("unknown parameter"))
}
})?;

let Some(error_type) = error_type else {
return Err(meta.error("missing error parameter"));
};
let Some(function_path) = function_path else {
return Err(meta.error("missing function parameter"));
};

Ok(Custom {
is_async,
error_type,
function_path,
})
}

fn is_async(&self) -> bool {
self.is_async
}

fn error_type(&self) -> TokenStream {
self.error_type.to_token_stream()
}

fn tokens(&self, expr: &TokenStream) -> TokenStream {
let function_path = &self.function_path;

if self.is_async {
quote! {
#function_path(&#expr).await
}
} else {
quote! {
#function_path(&#expr)
}
}
}
}
Loading