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
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
use proc_macro::TokenStream;
use quote::quote;
use serde::Serialize;
use syn::{
parse2, parse_macro_input, AttributeArgs, Data::Struct, DeriveInput, Fields::Named, NestedMeta,
Type::Path,
};
#[allow(non_snake_case)]
#[proc_macro_attribute]
pub fn Model(args: TokenStream, input: TokenStream) -> TokenStream {
let args = parse_macro_input!(args as AttributeArgs);
let mut ast = parse_macro_input!(input as DeriveInput);
impl_create_model(&args, &mut ast)
}
fn impl_create_model(args: &Vec<NestedMeta>, ast: &mut DeriveInput) -> TokenStream {
let model_name_ident = &ast.ident;
let model_name_str = model_name_ident.to_string();
if model_name_str.len() > 30 {
panic!("Model: `{model_name_str}` => Model name: Max size 30 characters.")
}
let mut trans_meta = Meta {
model_name: model_name_str.clone(),
..Default::default()
};
let mut html_id_map = std::collections::HashMap::<String, String>::new();
let mut add_trait_custom_valid = quote! {impl AdditionalValidation for #model_name_ident {}};
let mut add_trait_hooks = quote! {impl Hooks for #model_name_ident {}};
let add_trait_fixtures = quote! {impl Fixtures for #model_name_ident {}};
for nested_meta in args {
if let NestedMeta::Meta(meta) = nested_meta {
if let syn::Meta::NameValue(mnv) = meta {
if mnv.path.is_ident("database") {
if let syn::Lit::Str(lit_str) = &mnv.lit {
trans_meta.database_name = lit_str.value().trim().to_string();
} else {
panic!(
"Model: `{model_name_str}` => Could not determine value for \
parameter `database`. Use the `&str` type."
)
}
} else if mnv.path.is_ident("db_query_docs_limit") {
if let syn::Lit::Int(lit_int) = &mnv.lit {
trans_meta.db_query_docs_limit = lit_int.base10_parse::<u32>().unwrap();
} else {
panic!(
"Model: `{model_name_str}` => Could not determine value for \
parameter `db_query_docs_limit`. Use the `&str` type."
)
}
} else if mnv.path.is_ident("is_add_doc") {
if let syn::Lit::Bool(lit_bool) = &mnv.lit {
trans_meta.is_add_doc = lit_bool.value;
} else {
panic!(
"Model: `{model_name_str}` => Could not determine value for \
parameter `is_add_docs`. Use the `bool` type."
)
}
} else if mnv.path.is_ident("is_up_doc") {
if let syn::Lit::Bool(lit_bool) = &mnv.lit {
trans_meta.is_up_doc = lit_bool.value;
} else {
panic!(
"Model: `{model_name_str}` => Could not determine value for \
parameter `is_up_docs`. Use the `bool` type."
)
}
} else if mnv.path.is_ident("is_del_doc") {
if let syn::Lit::Bool(lit_bool) = &mnv.lit {
trans_meta.is_del_doc = lit_bool.value;
} else {
panic!(
"Model: `{model_name_str}` => Could not determine value for \
parameter `is_del_docs`. Use the `bool` type."
)
}
} else if mnv.path.is_ident("ignore_fields") {
if let syn::Lit::Str(lit_str) = &mnv.lit {
let mut value = lit_str.value();
value.retain(|chr| !chr.is_whitespace());
trans_meta.ignore_fields = value
.to_lowercase()
.split(',')
.map(|item| item.to_string())
.collect();
} else {
panic!(
"Model: `{model_name_str}` => Could not determine value for \
parameter `ignore_fields`. Use the type `&str` in \
the format - <field_name, field_name>."
)
}
} else if mnv.path.is_ident("is_use_add_valid") {
if let syn::Lit::Bool(lit_bool) = &mnv.lit {
trans_meta.is_use_add_valid = lit_bool.value;
if lit_bool.value {
add_trait_custom_valid = quote! {};
}
} else {
panic!(
"Model: `{model_name_str}` => Could not determine value for \
parameter `is_use_add_valid`. Use the `bool` type."
)
}
} else if mnv.path.is_ident("is_use_hooks") {
if let syn::Lit::Bool(lit_bool) = &mnv.lit {
trans_meta.is_use_hooks = lit_bool.value;
if lit_bool.value {
add_trait_hooks = quote! {};
}
} else {
panic!(
"Model: `{model_name_str}` => Could not determine value for \
parameter `is_use_hooks`. Use the `bool` type."
)
}
} else {
panic!(
"Model: `{model_name_str}` => Invalid parameter! => \
Valid Parameters: database | db_client_name | db_query_docs_limit | \
is_add_doc | is_up_doc | is_del_doc | ignore_fields | \
is_use_add_valid | is_use_hooks"
)
}
} else {
panic!("Model: `{model_name_str}` => syn::Meta::NameValue is missing.")
}
}
}
if let Struct(ref mut data) = &mut ast.data {
if let Named(ref mut fields) = &mut data.fields {
let fields = &mut fields.named;
for field in fields.clone() {
if let Some(ident) = &field.ident {
let field_name = ident.to_string();
if field_name == "hash" {
panic!("Model: `{model_name_str}` => The field named `hash` is reserved.")
} else if field_name == "created_at" {
panic!(
"Model: `{model_name_str}` => The field named `created_at` is reserved."
)
} else if field_name == "updated_at" {
panic!(
"Model: `{model_name_str}` => The field named `updated_at` is reserved."
)
}
}
}
let new_hash_field: syn::FieldsNamed = parse2(quote! {
{pub hash: HiddenHash}
})
.unwrap_or_else(|err| panic!("{}", err.to_string()));
let new_hash_field = new_hash_field.named.first().unwrap().to_owned();
fields.push(new_hash_field);
let new_created_at_field: syn::FieldsNamed = parse2(quote! {
{pub created_at: HiddenDateTime}
})
.unwrap_or_else(|err| panic!("{}", err.to_string()));
let new_created_at_field = new_created_at_field.named.first().unwrap().to_owned();
fields.push(new_created_at_field);
let new_updated_at_field: syn::FieldsNamed = parse2(quote! {
{pub updated_at: HiddenDateTime}
})
.unwrap_or_else(|err| panic!("{}", err.to_string()));
let new_updated_at_field = new_updated_at_field.named.first().unwrap().to_owned();
fields.push(new_updated_at_field);
trans_meta.fields_count = fields.len();
for field in fields {
let mut field_name = String::new();
let mut field_type = String::new();
if let Some(ident) = &field.ident {
field_name = ident.to_string();
trans_meta.fields_name.push(field_name.clone());
}
if let Path(ty) = &field.ty {
field_type = {
let tmp_str = quote! {#ty}.to_string();
let tmp_vec = tmp_str.split("::").collect::<Vec<&str>>();
tmp_vec[tmp_vec.len() - 1].trim().to_string()
};
let field_info = get_field_info(
model_name_str.as_str(),
field_name.as_str(),
field_type.as_str(),
)
.unwrap();
trans_meta
.field_value_type_map
.insert(field_name.clone(), field_info.0.to_string());
}
trans_meta
.field_type_map
.insert(field_name.clone(), field_type);
html_id_map.insert(
field_name.clone(),
get_html_id(model_name_str.as_str(), field_name.as_str()),
);
field.attrs = Vec::new();
}
} else {
panic!("Model: `{model_name_str}` => Expected a struct with named fields.")
}
}
for field_name in trans_meta.ignore_fields.iter() {
if !trans_meta.fields_name.contains(field_name) {
panic!(
"Model: `{model_name_str}` => Model does not have an ignored field named `{field_name}`."
)
}
}
let trans_meta_json = match serde_json::to_string(&trans_meta) {
Ok(json_line) => json_line,
Err(err) => panic!("Model: `{model_name_str}` => {0:?}", err),
};
let html_id_map_json = match serde_json::to_string(&html_id_map) {
Ok(json_line) => json_line,
Err(err) => panic!("Model: `{model_name_str}` => {0:?}", err),
};
let output = quote! {
#ast
impl Main for #model_name_ident {
fn key() -> Result<String, Box<dyn std::error::Error>> {
let re = regex::Regex::new(r"(?P<upper_chr>[A-Z])")?;
Ok(format!(
"{}__{}__{}",
SERVICE_NAME.trim(),
re.replace_all(stringify!(#model_name_ident), "_$upper_chr"),
UNIQUE_APP_KEY.trim().to_string()
)
.to_lowercase())
}
fn custom_default_to_json_val() -> Result<serde_json::Value, Box<dyn std::error::Error>>
where
Self: serde::de::DeserializeOwned + Sized,
{
let mut instance_json_val = serde_json::to_value(Self::custom_default())?;
let html_id_map =
serde_json::from_str::<std::collections::HashMap<&str, &str>>(&#html_id_map_json)?;
for (field_name, id_name) in html_id_map {
if let Some(required) = instance_json_val.get(field_name).unwrap().get("required") {
let is_required = required.as_bool().unwrap();
if is_required {
if (instance_json_val.get(field_name).unwrap().get("disabled").unwrap().as_bool().unwrap()
|| instance_json_val.get(field_name).unwrap().get("readonly").unwrap().as_bool().unwrap()
|| instance_json_val.get(field_name).unwrap().get("is_hide").unwrap().as_bool().unwrap()) {
Err(format!(
"Field: `{}` => Attribute required=true incompatible with \
disabled=true or readonly=true or is_hide=true.",
field_name
))?
}
}
}
if let Some(arr) = instance_json_val.get(field_name).unwrap().get("thumbnails") {
let mut arr = serde_json::from_value::<Vec<(String, u32)>>(arr.clone())?;
arr.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap());
let valid_size_names: [&str; 4] = ["xs", "sm", "md", "lg"];
for size in arr.iter() {
if !valid_size_names.contains(&size.0.as_str()) {
Err(format!(
"Field: `{}` => \
Valid size names - `xs`, `sm`, `md`, `lg`.",
field_name
))?
}
}
*instance_json_val
.get_mut(field_name)
.unwrap()
.get_mut("thumbnails")
.unwrap() = serde_json::json!(arr);
}
if let Some(val) = instance_json_val.get(field_name).unwrap().get("value") {
if !val.is_null() {
Err(format!(
"Field: `{}` => \
For default values, use the `default` field attribute.",
field_name
))?
}
}
if let Some(field_type) = instance_json_val.get(field_name).unwrap().get("field_type") {
if field_type.as_str().unwrap().contains("Dyn") {
if let Some(options) = instance_json_val.get(field_name).unwrap().get("options") {
if options.as_array().unwrap().len() > 0 {
Err(format!(
"Field: `{}` => \
For dynamic field types, the `options` parameter must be an empty vector.",
field_name
))?
}
}
}
}
*instance_json_val
.get_mut(field_name)
.unwrap()
.get_mut("id")
.unwrap() = serde_json::json!(id_name);
*instance_json_val
.get_mut(field_name)
.unwrap()
.get_mut("name")
.unwrap() = serde_json::json!(field_name);
}
Ok(instance_json_val)
}
fn generate_metadata() -> Result<Meta, Box<dyn std::error::Error>>
where
Self: serde::de::DeserializeOwned + Sized,
{
let re = regex::Regex::new(r"(?P<upper_chr>[A-Z])").unwrap();
let mut meta = serde_json::from_str::<Meta>(&#trans_meta_json)?;
let service_name: String = SERVICE_NAME.trim().to_string();
meta.app_name = APP_NAME.trim().to_string();
meta.unique_app_key = UNIQUE_APP_KEY.trim().to_string();
meta.service_name = service_name.clone();
if meta.database_name.is_empty() {
meta.database_name = format!(
"{}__{}__{}",
meta.app_name,
DATABASE_NAME.trim().to_string(),
meta.unique_app_key);
}
if meta.db_query_docs_limit == 0 {
meta.db_query_docs_limit = DB_QUERY_DOCS_LIMIT;
}
meta.collection_name = format!(
"{}_{}",
service_name,
re.replace_all(&meta.model_name[..], "_$upper_chr")
)
.to_lowercase();
let mut default_value_map = std::collections::HashMap::<String, serde_json::Value>::new();
let model_json = Self::custom_default_to_json_val()?;
for (field_name, field_type) in meta.field_type_map.iter() {
let default = if let Some(val) = model_json.get(field_name).unwrap().get("default") {
val.clone()
} else if let Some(val) = model_json.get(field_name).unwrap().get("checked") {
val.clone()
} else {
serde_json::json!(null)
};
default_value_map.insert(field_name.to_string(), default);
if !meta.is_use_hash_slug && field_type == "AutoSlug" {
let flag = model_json
.get(field_name)
.unwrap()
.get("slug_sources")
.unwrap()
.as_array()
.unwrap()
.iter()
.map(|item| item.as_str().unwrap())
.any(|item| item == "hash");
if flag {
meta.is_use_hash_slug = flag;
}
}
}
meta.default_value_map = default_value_map;
meta.model_json = model_json;
Ok(meta)
}
fn hash(&self) -> String {
self.hash.value.clone().unwrap_or_default()
}
fn set_hash(&mut self, value: String) {
self.hash.value = Some(value);
}
fn obj_id(&self) -> Result<Option<mongodb::bson::oid::ObjectId>, Box<dyn std::error::Error>> {
let hash = self.hash.value.clone().unwrap_or_default();
if let Ok(obj_id) = mongodb::bson::oid::ObjectId::parse_str(hash.as_str()) {
return Ok(Some(obj_id));
}
Ok(None)
}
fn set_obj_id(&mut self, obj_id: mongodb::bson::oid::ObjectId) {
self.hash.value = Some(obj_id.to_hex());
}
fn created_at(&self) -> String {
self.created_at.value.clone().unwrap_or_default()
}
fn set_created_at(&mut self, value: String) {
self.created_at.value = Some(value);
}
fn updated_at(&self) -> String {
self.updated_at.value.clone().unwrap_or_default()
}
fn set_updated_at(&mut self, value: String) {
self.updated_at.value = Some(value);
}
fn self_to_json_val(&self)
-> Result<serde_json::Value, Box<dyn std::error::Error>> {
Ok(serde_json::to_value(self)?)
}
}
#add_trait_custom_valid
#add_trait_hooks
#add_trait_fixtures
impl Caching for #model_name_ident {}
impl Validation for #model_name_ident {}
impl Converters for #model_name_ident {}
impl QCommons for #model_name_ident {}
impl QPaladins for #model_name_ident {}
};
TokenStream::from(output)
}
#[derive(Serialize)]
struct Meta {
pub model_name: String,
pub app_name: String,
pub unique_app_key: String,
pub service_name: String,
pub database_name: String,
pub db_query_docs_limit: u32,
pub collection_name: String, pub fields_count: usize,
pub fields_name: Vec<String>,
pub is_add_doc: bool,
pub is_up_doc: bool,
pub is_del_doc: bool,
pub is_use_add_valid: bool,
pub is_use_hooks: bool,
pub is_use_hash_slug: bool,
pub field_value_type_map: std::collections::HashMap<String, String>,
pub field_type_map: std::collections::HashMap<String, String>,
pub default_value_map: std::collections::HashMap<String, serde_json::Value>,
pub ignore_fields: Vec<String>,
pub option_str_map: std::collections::HashMap<String, Vec<String>>,
pub option_i32_map: std::collections::HashMap<String, Vec<i32>>,
pub option_i64_map: std::collections::HashMap<String, Vec<i64>>,
pub option_f64_map: std::collections::HashMap<String, Vec<f64>>,
pub model_json: serde_json::Value,
}
impl Default for Meta {
fn default() -> Self {
Meta {
model_name: String::new(),
app_name: String::new(),
unique_app_key: String::new(),
service_name: String::new(),
database_name: String::new(),
db_query_docs_limit: 0_u32,
collection_name: String::new(),
fields_count: 0_usize,
fields_name: Vec::new(),
is_add_doc: true,
is_up_doc: true,
is_del_doc: true,
is_use_add_valid: false,
is_use_hooks: false,
is_use_hash_slug: false,
field_value_type_map: std::collections::HashMap::new(),
field_type_map: std::collections::HashMap::new(),
default_value_map: std::collections::HashMap::new(),
ignore_fields: Vec::new(),
option_str_map: std::collections::HashMap::new(),
option_i32_map: std::collections::HashMap::new(),
option_i64_map: std::collections::HashMap::new(),
option_f64_map: std::collections::HashMap::new(),
model_json: serde_json::json!(null),
}
}
}
fn get_field_info<'a>(
model_name: &'a str,
field_name: &'a str,
field_type: &'a str,
) -> Result<(&'a str, &'a str), Box<dyn std::error::Error>> {
let info: (&'a str, &'a str) = match field_type {
"CheckBox" => ("bool", "checkbox"),
"InputColor" => ("String", "color"),
"InputDate" => ("String", "date"),
"InputDateTime" => ("String", "datetime"),
"InputEmail" => ("String", "email"),
"InputFile" => ("String", "file"),
"InputImage" => ("String", "file"),
"NumberI32" => ("i32", "number"),
"NumberU32" => ("u32", "number"),
"NumberI64" => ("i64", "number"),
"NumberF64" => ("f64", "number"),
"InputPassword" => ("String", "password"),
"RadioText" => ("String", "radio"),
"RadioI32" => ("i32", "radio"),
"RadioU32" => ("u32", "radio"),
"RadioI64" => ("i64", "radio"),
"RadioF64" => ("f64", "radio"),
"RangeI32" => ("i32", "range"),
"RangeU32" => ("u32", "range"),
"RangeI64" => ("i64", "range"),
"RangeF64" => ("f64", "range"),
"InputPhone" => ("String", "tel"),
"InputText" => ("String", "text"),
"AutoSlug" => ("String", "text"),
"InputUrl" => ("String", "url"),
"InputIP" => ("String", "text"),
"InputIPv4" => ("String", "text"),
"InputIPv6" => ("String", "text"),
"TextArea" => ("String", "textarea"),
"SelectText" => ("String", "select"),
"SelectTextDyn" => ("String", "select"),
"SelectTextMult" => ("Vec<String>", "select"),
"SelectTextMultDyn" => ("Vec<String>", "select"),
"SelectI32" => ("i32", "select"),
"SelectI32Dyn" => ("i32", "select"),
"SelectI32Mult" => ("Vec<i32>", "select"),
"SelectI32MultDyn" => ("Vec<i32>", "select"),
"SelectU32" => ("u32", "select"),
"SelectU32Dyn" => ("u32", "select"),
"SelectU32Mult" => ("Vec<u32>", "select"),
"SelectU32MultDyn" => ("Vec<u32>", "select"),
"SelectI64" => ("i64", "select"),
"SelectI64Dyn" => ("i64", "select"),
"SelectI64Mult" => ("Vec<i64>", "select"),
"SelectI64MultDyn" => ("Vec<i64>", "select"),
"SelectF64" => ("f64", "select"),
"SelectF64Dyn" => ("f64", "select"),
"SelectF64Mult" => ("Vec<f64>", "select"),
"SelectF64MultDyn" => ("Vec<f64>", "select"),
"HiddenHash" => ("String", "text"),
"HiddenDateTime" => ("String", "datetime"),
_ => Err(format!(
"Model: `{model_name}` > Field: `{field_name}` > Field type: `{field_type}` => \
Invalid field type."
))?,
};
Ok(info)
}
fn get_html_id<'a>(model_name: &'a str, field_name: &'a str) -> String {
let field_name_upper = field_name
.split('_')
.map(|word| word[0..1].to_uppercase() + &word[1..])
.collect::<Vec<String>>()
.join("");
format!("{model_name}-{field_name_upper}")
}