armature-framework 0.2.2

A modern, type-safe HTTP framework for Rust inspired by Angular and NestJS. Features dependency injection, decorators, middleware, authentication (JWT/OAuth2/SAML), validation, OpenAPI/Swagger, caching, job queues, and observability.
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
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
# GraphQL Guide

This guide explains how to use GraphQL with the Armature framework, inspired by NestJS's @nestjs/graphql.

## Overview

Armature provides optional GraphQL support through the `armature-graphql` module, built on top of `async-graphql`. This integration enables you to build type-safe GraphQL APIs with full dependency injection support and programmatic schema generation.

## Features

✅ **Type-Safe Schema** - Compile-time verified GraphQL types
✅ **Programmatic Schema** - Build schemas programmatically like NestJS
✅ **Queries & Mutations** - Full CRUD operations support
✅ **Subscriptions** - Real-time GraphQL subscriptions
✅ **DI Integration** - Services injected into resolvers
✅ **Decorator-Style** - Rust procedural macros for clean syntax
✅ **GraphiQL/Playground** - Built-in query interface
✅ **Schema Introspection** - Automatic API documentation

## Installation

Add the GraphQL feature to your `Cargo.toml`:

```toml
[dependencies]
armature-framework = { version = "0.1", features = ["graphql"] }
armature-graphql = "0.1"
```

## Quick Start

### 1. Define Your Types

```rust
use armature_graphql::{SimpleObject, ID};

#[derive(SimpleObject)]
struct Book {
    id: ID,
    title: String,
    author: String,
    year: i32,
}
```

### 2. Create Query Root

```rust
use armature_graphql::Object;

struct QueryRoot {
    book_service: BookService,
}

#[Object]
impl QueryRoot {
    async fn books(&self) -> Vec<Book> {
        self.book_service.get_all_books()
    }

    async fn book(&self, id: ID) -> Option<Book> {
        self.book_service.get_book_by_id(&id)
    }
}
```

### 3. Create Mutation Root

```rust
struct MutationRoot {
    book_service: BookService,
}

#[Object]
impl MutationRoot {
    async fn create_book(&self, title: String, author: String) -> Book {
        self.book_service.create_book(title, author)
    }
}
```

### 4. Build Schema Programmatically (NestJS-style)

```rust
use armature_graphql::{ProgrammaticSchemaBuilder, EmptySubscription};

// Using the programmatic builder
let schema = ProgrammaticSchemaBuilder::new()
    .query(QueryRoot { book_service: book_service.clone() })
    .mutation(MutationRoot { book_service: book_service.clone() })
    .subscription(EmptySubscription)
    .add_service(book_service)  // Add to schema context
    .build();

// Or use the standard Schema::build
let schema = Schema::build(
    QueryRoot { book_service },
    MutationRoot { book_service },
    EmptySubscription
).finish();
```

### 5. Create GraphQL Endpoint

```rust
router.add_route(Route {
    method: HttpMethod::POST,
    path: "/graphql".to_string(),
    handler: Arc::new(move |req| {
        let schema = schema.clone();
        Box::pin(async move {
            // Handle GraphQL request
            let gql_req: GraphQLRequest = req.json()?;
            let request = async_graphql::Request::new(gql_req.query);
            let response = schema.execute(request).await;

            let json = serde_json::to_value(&response)?;
            HttpResponse::ok().with_json(&json)
        })
    }),
});
```

## Type System

### Simple Objects

For simple data types:

```rust
#[derive(SimpleObject)]
struct User {
    id: ID,
    name: String,
    email: String,
    age: i32,
}
```

### Complex Objects with Resolvers

For types with computed fields:

```rust
struct User {
    id: ID,
    name: String,
}

#[Object]
impl User {
    // Simple field
    async fn id(&self) -> &ID {
        &self.id
    }

    // Computed field
    async fn full_name(&self, format: Option<String>) -> String {
        match format.as_deref() {
            Some("upper") => self.name.to_uppercase(),
            Some("lower") => self.name.to_lowercase(),
            _ => self.name.clone(),
        }
    }

    // Field with service injection (via context)
    async fn posts(&self, ctx: &Context<'_>) -> Vec<Post> {
        let service = ctx.data::<PostService>().unwrap();
        service.get_user_posts(&self.id)
    }
}
```

### Enums

```rust
#[derive(Enum, Copy, Clone, Eq, PartialEq)]
enum Role {
    Admin,
    User,
    Guest,
}
```

### Unions

```rust
#[derive(Union)]
enum SearchResult {
    User(User),
    Post(Post),
    Comment(Comment),
}
```

### Input Objects

For mutation arguments:

```rust
#[derive(InputObject)]
struct CreateUserInput {
    name: String,
    email: String,
    age: Option<i32>,
}

#[Object]
impl MutationRoot {
    async fn create_user(&self, input: CreateUserInput) -> User {
        // Create user from input
    }
}
```

## Queries

### Basic Query

```rust
#[Object]
impl QueryRoot {
    async fn hello(&self) -> &str {
        "Hello, World!"
    }

    async fn users(&self) -> Vec<User> {
        self.user_service.get_all()
    }
}
```

**GraphQL:**
```graphql
query {
    hello
    users {
        id
        name
    }
}
```

### Query with Arguments

```rust
#[Object]
impl QueryRoot {
    async fn user(&self, id: ID) -> Result<User> {
        self.user_service
            .get_by_id(&id)
            .ok_or("User not found".into())
    }

    async fn search_users(
        &self,
        query: String,
        limit: Option<i32>,
    ) -> Vec<User> {
        self.user_service.search(&query, limit.unwrap_or(10))
    }
}
```

**GraphQL:**
```graphql
query {
    user(id: "123") {
        id
        name
    }

    searchUsers(query: "john", limit: 5) {
        id
        name
    }
}
```

### Nested Queries

```rust
struct User {
    id: ID,
    name: String,
}

#[Object]
impl User {
    async fn id(&self) -> &ID { &self.id }
    async fn name(&self) -> &str { &self.name }

    async fn posts(&self, ctx: &Context<'_>) -> Vec<Post> {
        ctx.data::<PostService>()
            .unwrap()
            .get_user_posts(&self.id)
    }
}

struct Post {
    id: ID,
    title: String,
}

#[Object]
impl Post {
    async fn id(&self) -> &ID { &self.id }
    async fn title(&self) -> &str { &self.title }

    async fn author(&self, ctx: &Context<'_>) -> User {
        ctx.data::<UserService>()
            .unwrap()
            .get_by_id(&self.author_id)
    }
}
```

**GraphQL:**
```graphql
query {
    user(id: "123") {
        name
        posts {
            title
            author {
                name
            }
        }
    }
}
```

## Mutations

### Basic Mutations

```rust
#[Object]
impl MutationRoot {
    async fn create_user(&self, name: String, email: String) -> User {
        self.user_service.create(name, email)
    }

    async fn update_user(&self, id: ID, name: String) -> Result<User> {
        self.user_service
            .update(&id, name)
            .ok_or("User not found".into())
    }

    async fn delete_user(&self, id: ID) -> bool {
        self.user_service.delete(&id)
    }
}
```

**GraphQL:**
```graphql
mutation {
    createUser(name: "John", email: "john@example.com") {
        id
        name
    }

    updateUser(id: "123", name: "Jane") {
        id
        name
    }

    deleteUser(id: "123")
}
```

### Mutations with Input Objects

```rust
#[derive(InputObject)]
struct CreatePostInput {
    title: String,
    content: String,
    author_id: ID,
    tags: Vec<String>,
}

#[Object]
impl MutationRoot {
    async fn create_post(&self, input: CreatePostInput) -> Post {
        self.post_service.create(input)
    }
}
```

**GraphQL:**
```graphql
mutation {
    createPost(input: {
        title: "My Post"
        content: "Post content"
        authorId: "123"
        tags: ["rust", "graphql"]
    }) {
        id
        title
    }
}
```

## Subscriptions

### Real-time Updates

```rust
use armature_graphql::Subscription;
use futures_util::Stream;

struct SubscriptionRoot;

#[Subscription]
impl SubscriptionRoot {
    async fn books(&self) -> impl Stream<Item = Book> {
        // Return a stream of books
        async_stream::stream! {
            loop {
                tokio::time::sleep(Duration::from_secs(1)).await;
                yield Book {
                    id: ID::from("1"),
                    title: "New Book".to_string(),
                    author: "Author".to_string(),
                    year: 2024,
                };
            }
        }
    }
}
```

**GraphQL:**
```graphql
subscription {
    books {
        id
        title
    }
}
```

## Programmatic Schema Building (NestJS-style)

Armature provides a `ProgrammaticSchemaBuilder` for building GraphQL schemas programmatically, similar to NestJS's approach:

```rust
use armature_graphql::ProgrammaticSchemaBuilder;

// Create services
let user_service = UserService::default();
let post_service = PostService::default();

// Create resolvers with injected services
let query = QueryRoot {
    user_service: user_service.clone(),
    post_service: post_service.clone(),
};

let mutation = MutationRoot {
    user_service: user_service.clone(),
    post_service: post_service.clone(),
};

// Build schema programmatically
let schema = ProgrammaticSchemaBuilder::new()
    .query(query)
    .mutation(mutation)
    .subscription(EmptySubscription)
    .add_service(user_service)    // Add to context
    .add_service(post_service)    // Add to context
    .build();
```

### Comparison with NestJS

**NestJS (@nestjs/graphql):**
```typescript
@Module({
  imports: [
    GraphQLModule.forRoot({
      autoSchemaFile: true,
    }),
  ],
  providers: [UserService, UserResolver],
})
export class AppModule {}

@Resolver(() => User)
export class UserResolver {
  constructor(private userService: UserService) {}

  @Query(() => [User])
  users() {
    return this.userService.findAll();
  }
}
```

**Armature (armature-graphql):**
```rust
#[injectable]
#[derive(Clone)]
struct UserService { }

struct QueryRoot {
    user_service: UserService,
}

#[Object]
impl QueryRoot {
    async fn users(&self) -> Vec<User> {
        self.user_service.find_all()
    }
}

let schema = ProgrammaticSchemaBuilder::new()
    .query(QueryRoot { user_service })
    .mutation(EmptyMutation)
    .subscription(EmptySubscription)
    .build();
```

## Dependency Injection with GraphQL

### Inject Services into Resolvers

```rust
// Define your service
#[injectable]
#[derive(Clone)]
struct UserService {
    database: DatabaseService,
}

// Method 1: Constructor injection (NestJS-style)
struct QueryRoot {
    user_service: UserService,
}

#[Object]
impl QueryRoot {
    async fn users(&self) -> Vec<User> {
        self.user_service.get_all()
    }
}

// Method 2: Context injection
// Add service to GraphQL context
let schema = ProgrammaticSchemaBuilder::new()
    .query(query)
    .add_service(user_service)  // Available in context
    .build();

// Use in resolver
#[Object]
impl QueryRoot {
    async fn users(&self, ctx: &Context<'_>) -> Vec<User> {
        let service = ctx.data::<UserService>().unwrap();
        service.get_all()
    }
}
```

## Error Handling

### Custom Errors

```rust
use armature_graphql::Error;

#[Object]
impl QueryRoot {
    async fn user(&self, id: ID) -> Result<User> {
        self.user_service
            .get_by_id(&id)
            .ok_or_else(|| Error::new("User not found"))
    }

    async fn validate_user(&self, email: String) -> Result<bool> {
        if !email.contains('@') {
            return Err(Error::new("Invalid email format"));
        }
        Ok(true)
    }
}
```

### Field Errors

```rust
#[Object]
impl User {
    async fn sensitive_data(&self, ctx: &Context<'_>) -> Result<String> {
        let auth = ctx.data::<AuthService>().unwrap();

        if !auth.is_authorized(&self.id) {
            return Err(Error::new("Unauthorized"));
        }

        Ok(self.sensitive_data.clone())
    }
}
```

## GraphQL Playground

### Built-in Playground

Armature provides two playground options:

#### GraphiQL (Lightweight)

```rust
use armature_graphql::graphiql_html;

router.add_route(Route {
    method: HttpMethod::GET,
    path: "/playground".to_string(),
    handler: Arc::new(move |_req| {
        Box::pin(async move {
            let html = graphiql_html("/graphql");
            Ok(HttpResponse::ok()
                .with_header("Content-Type".into(), "text/html".into())
                .with_body(html.into_bytes()))
        })
    }),
});
```

#### GraphQL Playground

```rust
use armature_graphql::graphql_playground_html;

let html = graphql_playground_html("/graphql");
```

## Best Practices

### 1. Use Input Objects for Complex Mutations

**Good:**
```rust
#[derive(InputObject)]
struct CreateUserInput {
    name: String,
    email: String,
    role: Role,
}

async fn create_user(&self, input: CreateUserInput) -> User
```

**Avoid:**
```rust
async fn create_user(&self, name: String, email: String, role: Role) -> User
```

### 2. Implement Pagination

```rust
#[derive(SimpleObject)]
struct UserConnection {
    edges: Vec<UserEdge>,
    page_info: PageInfo,
}

#[derive(SimpleObject)]
struct UserEdge {
    node: User,
    cursor: String,
}

#[derive(SimpleObject)]
struct PageInfo {
    has_next_page: bool,
    has_previous_page: bool,
}

#[Object]
impl QueryRoot {
    async fn users(&self, first: i32, after: Option<String>) -> UserConnection {
        self.user_service.paginate(first, after)
    }
}
```

### 3. Use DataLoader for N+1 Queries

```rust
use async_graphql::dataloader::*;

struct UserLoader {
    user_service: UserService,
}

#[async_trait::async_trait]
impl Loader<ID> for UserLoader {
    type Value = User;
    type Error = Arc<Error>;

    async fn load(&self, keys: &[ID]) -> Result<HashMap<ID, User>, Self::Error> {
        Ok(self.user_service.get_by_ids(keys))
    }
}
```

### 4. Add Field Descriptions

```rust
#[Object]
impl QueryRoot {
    /// Get all users in the system
    #[graphql(desc = "Retrieve a list of all users")]
    async fn users(&self) -> Vec<User> {
        self.user_service.get_all()
    }
}
```

### 5. Use Guards for Authorization

```rust
use async_graphql::Guard;

struct RoleGuard {
    role: Role,
}

#[async_trait::async_trait]
impl Guard for RoleGuard {
    async fn check(&self, ctx: &Context<'_>) -> Result<()> {
        let user = ctx.data::<CurrentUser>()?;
        if user.role == self.role {
            Ok(())
        } else {
            Err("Unauthorized".into())
        }
    }
}

#[Object]
impl MutationRoot {
    #[graphql(guard = "RoleGuard { role: Role::Admin }")]
    async fn delete_user(&self, id: ID) -> bool {
        self.user_service.delete(&id)
    }
}
```

## Testing

### Unit Testing Resolvers

```rust
#[tokio::test]
async fn test_query_users() {
    let service = UserService::default();
    let query = QueryRoot { user_service: service };

    let users = query.users().await;
    assert!(!users.is_empty());
}
```

### Integration Testing Schema

```rust
#[tokio::test]
async fn test_graphql_query() {
    let schema = create_schema();

    let query = r#"
        query {
            users {
                id
                name
            }
        }
    "#;

    let req = async_graphql::Request::new(query);
    let res = schema.execute(req).await;

    assert!(res.errors.is_empty());
    assert!(res.data.is_object());
}
```

## Performance Tips

1. **Use DataLoader** - Batch database queries
2. **Limit Query Depth** - Prevent deeply nested queries
3. **Add Query Complexity** - Limit computational cost
4. **Cache Results** - Use Redis or in-memory cache
5. **Optimize N+1** - Use DataLoader or JOIN queries

## Common Patterns

### Relay-Style Pagination

```rust
#[derive(SimpleObject)]
struct Connection<T> {
    edges: Vec<Edge<T>>,
    page_info: PageInfo,
}
```

### Error Union Pattern

```rust
#[derive(Union)]
enum UserResult {
    Success(User),
    Error(UserError),
}
```

### Batch Mutations

```rust
async fn batch_create_users(&self, inputs: Vec<CreateUserInput>) -> Vec<User>
```

## Summary

Armature's GraphQL support provides:

✅ **Type-Safe** - Compile-time schema validation
✅ **DI Integration** - Services injected into resolvers
✅ **Full Featured** - Queries, mutations, subscriptions
✅ **Developer Friendly** - Built-in playground
✅ **Production Ready** - Error handling, pagination, guards
✅ **Performant** - DataLoader, caching support

For more examples, see `examples/graphql_api.rs` in the repository.