postrust_graphql/
context.rs

1//! GraphQL context containing auth, database pool, and schema cache.
2
3use postrust_auth::AuthResult;
4use postrust_core::schema_cache::SchemaCacheRef;
5use sqlx::PgPool;
6
7/// Context available to all GraphQL resolvers.
8pub struct GraphQLContext {
9    /// Database connection pool.
10    pub pool: PgPool,
11    /// Schema cache for table/column metadata.
12    pub schema_cache: SchemaCacheRef,
13    /// Authentication result with role and claims.
14    pub auth: AuthResult,
15}
16
17impl GraphQLContext {
18    /// Create a new GraphQL context.
19    pub fn new(pool: PgPool, schema_cache: SchemaCacheRef, auth: AuthResult) -> Self {
20        Self {
21            pool,
22            schema_cache,
23            auth,
24        }
25    }
26
27    /// Get the current role.
28    pub fn role(&self) -> &str {
29        &self.auth.role
30    }
31
32    /// Get a claim value.
33    pub fn claim(&self, key: &str) -> Option<&serde_json::Value> {
34        self.auth.claims.get(key)
35    }
36}
37
38#[cfg(test)]
39mod tests {
40    use super::*;
41    use std::collections::HashMap;
42
43    fn create_test_auth() -> AuthResult {
44        let mut claims = HashMap::new();
45        claims.insert("user_id".into(), serde_json::json!(123));
46        claims.insert("role".into(), serde_json::json!("admin"));
47
48        AuthResult {
49            role: "authenticated".into(),
50            claims,
51        }
52    }
53
54    #[test]
55    fn test_context_role() {
56        let auth = create_test_auth();
57        // Note: We can't fully test without a pool, but we can test the auth part
58        assert_eq!(auth.role, "authenticated");
59    }
60
61    #[test]
62    fn test_context_claim() {
63        let auth = create_test_auth();
64        assert_eq!(auth.claims.get("user_id"), Some(&serde_json::json!(123)));
65    }
66}