this-rs 0.0.9

Framework for building complex multi-entity REST and GraphQL APIs with many relationships
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
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
//! Utility functions for GraphQL execution

use anyhow::Result;
use graphql_parser::query::{Field, Value as GqlValue};
use serde_json::{Value, json};
use uuid::Uuid;

/// Get string argument from field
pub fn get_string_arg(field: &Field<String>, arg_name: &str) -> Option<String> {
    field
        .arguments
        .iter()
        .find(|(name, _)| name.as_str() == arg_name)
        .and_then(|(_, value)| {
            if let GqlValue::String(s) = value {
                Some(s.clone())
            } else {
                None
            }
        })
}

/// Get int argument from field
pub fn get_int_arg(field: &Field<String>, arg_name: &str) -> Option<i32> {
    field
        .arguments
        .iter()
        .find(|(name, _)| name.as_str() == arg_name)
        .and_then(|(_, value)| {
            if let GqlValue::Int(i) = value {
                Some(i.as_i64().unwrap_or(0) as i32)
            } else {
                None
            }
        })
}

/// Get JSON argument from field
pub fn get_json_arg(field: &Field<String>, arg_name: &str) -> Option<Value> {
    field
        .arguments
        .iter()
        .find(|(name, _)| name.as_str() == arg_name)
        .map(|(_, value)| gql_value_to_json(value))
}

/// Convert GraphQL value to JSON
pub fn gql_value_to_json(value: &GqlValue<String>) -> Value {
    match value {
        GqlValue::Null => Value::Null,
        GqlValue::Int(i) => json!(i.as_i64().unwrap_or(0)),
        GqlValue::Float(f) => json!(f),
        GqlValue::String(s) => json!(s),
        GqlValue::Boolean(b) => json!(b),
        GqlValue::Enum(e) => json!(e),
        GqlValue::List(list) => Value::Array(list.iter().map(gql_value_to_json).collect()),
        GqlValue::Object(obj) => {
            let mut map = serde_json::Map::new();
            for (k, v) in obj {
                map.insert(k.clone(), gql_value_to_json(v));
            }
            Value::Object(map)
        }
        GqlValue::Variable(_) => Value::Null, // Variables should be resolved before this
    }
}

/// Simple pluralization (can be improved)
pub fn pluralize(word: &str) -> String {
    if let Some(stripped) = word.strip_suffix('y') {
        format!("{}ies", stripped)
    } else if word.ends_with('s') || word.ends_with("sh") || word.ends_with("ch") {
        format!("{}es", word)
    } else {
        format!("{}s", word)
    }
}

/// Convert PascalCase to snake_case
pub fn pascal_to_snake(s: &str) -> String {
    let mut result = String::new();
    for (i, ch) in s.chars().enumerate() {
        if ch.is_uppercase() {
            if i > 0 {
                result.push('_');
            }
            result.push(ch.to_ascii_lowercase());
        } else {
            result.push(ch);
        }
    }
    result
}

/// Convert camelCase to snake_case
pub fn camel_to_snake(s: &str) -> String {
    let mut result = String::new();
    for (i, ch) in s.chars().enumerate() {
        if ch.is_uppercase() {
            if i > 0 {
                result.push('_');
            }
            result.push(ch.to_ascii_lowercase());
        } else {
            result.push(ch);
        }
    }
    result
}

/// Convert mutation name to entity type (e.g., "createOrder" -> "order")
pub fn mutation_name_to_entity_type(mutation_name: &str, prefix: &str) -> String {
    let name_without_prefix = mutation_name.strip_prefix(prefix).unwrap_or(mutation_name);
    pascal_to_snake(name_without_prefix)
}

/// Extract a UUID from a JSON value's "id" field
///
/// Tries to parse the `id` field as a UUID string. Returns `None` if the
/// field is missing or cannot be parsed.
pub fn extract_uuid_from_value(value: &Value) -> Option<Uuid> {
    value
        .get("id")
        .and_then(|v| v.as_str())
        .and_then(|s| Uuid::parse_str(s).ok())
}

/// Find link type from configuration
pub fn find_link_type(
    links: &[crate::core::link::LinkDefinition],
    source_type: &str,
    target_type: &str,
) -> Result<String> {
    for link_config in links {
        if link_config.source_type == source_type && link_config.target_type == target_type {
            return Ok(link_config.link_type.clone());
        }
    }
    anyhow::bail!(
        "No link configuration found for {} -> {}",
        source_type,
        target_type
    )
}

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

    // ---- gql_value_to_json tests ----

    #[cfg(feature = "graphql")]
    #[test]
    fn test_gql_value_to_json_null() {
        let result = gql_value_to_json(&GqlValue::Null);
        assert_eq!(result, Value::Null);
    }

    #[cfg(feature = "graphql")]
    #[test]
    fn test_gql_value_to_json_int() {
        let num = graphql_parser::query::Number::from(42i32);
        let result = gql_value_to_json(&GqlValue::Int(num));
        assert_eq!(result, serde_json::json!(42));
    }

    #[cfg(feature = "graphql")]
    #[test]
    fn test_gql_value_to_json_float() {
        let result = gql_value_to_json(&GqlValue::Float(3.15));
        assert_eq!(result, serde_json::json!(3.15));
    }

    #[cfg(feature = "graphql")]
    #[test]
    fn test_gql_value_to_json_string() {
        let result = gql_value_to_json(&GqlValue::String("hello".to_string()));
        assert_eq!(result, serde_json::json!("hello"));
    }

    #[cfg(feature = "graphql")]
    #[test]
    fn test_gql_value_to_json_boolean() {
        let result_true = gql_value_to_json(&GqlValue::Boolean(true));
        let result_false = gql_value_to_json(&GqlValue::Boolean(false));
        assert_eq!(result_true, serde_json::json!(true));
        assert_eq!(result_false, serde_json::json!(false));
    }

    #[cfg(feature = "graphql")]
    #[test]
    fn test_gql_value_to_json_enum() {
        let result = gql_value_to_json(&GqlValue::Enum("ACTIVE".to_string()));
        assert_eq!(result, serde_json::json!("ACTIVE"));
    }

    #[cfg(feature = "graphql")]
    #[test]
    fn test_gql_value_to_json_list() {
        let list = GqlValue::List(vec![
            GqlValue::Int(graphql_parser::query::Number::from(1i32)),
            GqlValue::Int(graphql_parser::query::Number::from(2i32)),
        ]);
        let result = gql_value_to_json(&list);
        assert_eq!(result, serde_json::json!([1, 2]));
    }

    #[cfg(feature = "graphql")]
    #[test]
    fn test_gql_value_to_json_object() {
        let mut obj = std::collections::BTreeMap::new();
        obj.insert("name".to_string(), GqlValue::String("Alice".to_string()));
        obj.insert(
            "age".to_string(),
            GqlValue::Int(graphql_parser::query::Number::from(30i32)),
        );
        let result = gql_value_to_json(&GqlValue::Object(obj));
        assert_eq!(result, serde_json::json!({"name": "Alice", "age": 30}));
    }

    #[cfg(feature = "graphql")]
    #[test]
    fn test_gql_value_to_json_variable() {
        let result = gql_value_to_json(&GqlValue::Variable("myVar".to_string()));
        assert_eq!(result, Value::Null);
    }

    // ---- pluralize tests ----

    #[cfg(feature = "graphql")]
    #[test]
    fn test_pluralize_regular() {
        assert_eq!(pluralize("order"), "orders");
    }

    #[cfg(feature = "graphql")]
    #[test]
    fn test_pluralize_ending_in_y() {
        assert_eq!(pluralize("baby"), "babies");
    }

    #[cfg(feature = "graphql")]
    #[test]
    fn test_pluralize_ending_in_s() {
        assert_eq!(pluralize("bus"), "buses");
    }

    #[cfg(feature = "graphql")]
    #[test]
    fn test_pluralize_ending_in_ch() {
        assert_eq!(pluralize("church"), "churches");
    }

    #[cfg(feature = "graphql")]
    #[test]
    fn test_pluralize_ending_in_sh() {
        assert_eq!(pluralize("dish"), "dishes");
    }

    // ---- pascal_to_snake tests ----

    #[cfg(feature = "graphql")]
    #[test]
    fn test_pascal_to_snake_multi_word() {
        assert_eq!(pascal_to_snake("OrderItem"), "order_item");
    }

    #[cfg(feature = "graphql")]
    #[test]
    fn test_pascal_to_snake_single_char() {
        assert_eq!(pascal_to_snake("A"), "a");
    }

    #[cfg(feature = "graphql")]
    #[test]
    fn test_pascal_to_snake_empty() {
        assert_eq!(pascal_to_snake(""), "");
    }

    #[cfg(feature = "graphql")]
    #[test]
    fn test_pascal_to_snake_already_lower() {
        assert_eq!(pascal_to_snake("order"), "order");
    }

    // ---- camel_to_snake tests ----

    #[cfg(feature = "graphql")]
    #[test]
    fn test_camel_to_snake_multi_word() {
        assert_eq!(camel_to_snake("createdAt"), "created_at");
    }

    #[cfg(feature = "graphql")]
    #[test]
    fn test_camel_to_snake_single_word() {
        assert_eq!(camel_to_snake("id"), "id");
    }

    // ---- mutation_name_to_entity_type tests ----

    #[cfg(feature = "graphql")]
    #[test]
    fn test_mutation_name_to_entity_type_create() {
        assert_eq!(
            mutation_name_to_entity_type("createOrder", "create"),
            "order"
        );
    }

    #[cfg(feature = "graphql")]
    #[test]
    fn test_mutation_name_to_entity_type_delete_pascal() {
        assert_eq!(
            mutation_name_to_entity_type("deleteUserProfile", "delete"),
            "user_profile"
        );
    }

    #[cfg(feature = "graphql")]
    #[test]
    fn test_mutation_name_to_entity_type_no_prefix_match() {
        // When prefix doesn't match, the whole name is used
        assert_eq!(
            mutation_name_to_entity_type("createOrder", "delete"),
            "create_order"
        );
    }

    // ---- find_link_type tests ----

    #[cfg(feature = "graphql")]
    fn make_link_def(
        source: &str,
        target: &str,
        link_type: &str,
    ) -> crate::core::link::LinkDefinition {
        crate::core::link::LinkDefinition {
            link_type: link_type.to_string(),
            source_type: source.to_string(),
            target_type: target.to_string(),
            forward_route_name: format!("{}s", target),
            reverse_route_name: source.to_string(),
            description: None,
            required_fields: None,
            auth: None,
        }
    }

    #[cfg(feature = "graphql")]
    #[test]
    fn test_find_link_type_found() {
        let links = vec![make_link_def("order", "invoice", "has_invoice")];
        let result = find_link_type(&links, "order", "invoice").expect("should find link type");
        assert_eq!(result, "has_invoice");
    }

    #[cfg(feature = "graphql")]
    #[test]
    fn test_find_link_type_not_found() {
        let links = vec![make_link_def("order", "invoice", "has_invoice")];
        let result = find_link_type(&links, "user", "car");
        assert!(result.is_err());
    }

    #[cfg(feature = "graphql")]
    #[test]
    fn test_find_link_type_multiple_configs() {
        let links = vec![
            make_link_def("order", "invoice", "has_invoice"),
            make_link_def("user", "car", "owner"),
        ];
        let result = find_link_type(&links, "user", "car")
            .expect("should find link type among multiple configs");
        assert_eq!(result, "owner");
    }

    // ---- get_string_arg / get_int_arg / get_json_arg tests ----

    #[cfg(feature = "graphql")]
    fn make_field(arguments: Vec<(String, GqlValue<String>)>) -> Field<String> {
        use graphql_parser::Pos;
        use graphql_parser::query::SelectionSet;
        Field {
            position: Pos { line: 1, column: 1 },
            alias: None,
            name: "test_field".to_string(),
            arguments,
            directives: vec![],
            selection_set: SelectionSet {
                span: (Pos { line: 1, column: 1 }, Pos { line: 1, column: 1 }),
                items: vec![],
            },
        }
    }

    #[cfg(feature = "graphql")]
    #[test]
    fn test_get_string_arg_present() {
        let field = make_field(vec![(
            "name".to_string(),
            GqlValue::String("Alice".to_string()),
        )]);
        let result = get_string_arg(&field, "name");
        assert_eq!(result, Some("Alice".to_string()));
    }

    #[cfg(feature = "graphql")]
    #[test]
    fn test_get_string_arg_missing() {
        let field = make_field(vec![]);
        let result = get_string_arg(&field, "name");
        assert_eq!(result, None);
    }

    #[cfg(feature = "graphql")]
    #[test]
    fn test_get_string_arg_wrong_type() {
        let field = make_field(vec![(
            "name".to_string(),
            GqlValue::Int(graphql_parser::query::Number::from(42i32)),
        )]);
        let result = get_string_arg(&field, "name");
        assert_eq!(result, None);
    }

    #[cfg(feature = "graphql")]
    #[test]
    fn test_get_int_arg_present() {
        let field = make_field(vec![(
            "limit".to_string(),
            GqlValue::Int(graphql_parser::query::Number::from(10i32)),
        )]);
        let result = get_int_arg(&field, "limit");
        assert_eq!(result, Some(10));
    }

    #[cfg(feature = "graphql")]
    #[test]
    fn test_get_int_arg_missing() {
        let field = make_field(vec![]);
        let result = get_int_arg(&field, "limit");
        assert_eq!(result, None);
    }

    #[cfg(feature = "graphql")]
    #[test]
    fn test_get_int_arg_wrong_type() {
        let field = make_field(vec![(
            "limit".to_string(),
            GqlValue::String("not_a_number".to_string()),
        )]);
        let result = get_int_arg(&field, "limit");
        assert_eq!(result, None);
    }

    #[cfg(feature = "graphql")]
    #[test]
    fn test_get_json_arg_present() {
        let field = make_field(vec![(
            "data".to_string(),
            GqlValue::String("hello".to_string()),
        )]);
        let result = get_json_arg(&field, "data");
        assert_eq!(result, Some(serde_json::json!("hello")));
    }

    #[cfg(feature = "graphql")]
    #[test]
    fn test_get_json_arg_missing() {
        let field = make_field(vec![]);
        let result = get_json_arg(&field, "data");
        assert_eq!(result, None);
    }
}