use postrust_auth::AuthResult;
use postrust_core::schema_cache::SchemaCacheRef;
use sqlx::PgPool;
pub struct GraphQLContext {
pub pool: PgPool,
pub schema_cache: SchemaCacheRef,
pub auth: AuthResult,
}
impl GraphQLContext {
pub fn new(pool: PgPool, schema_cache: SchemaCacheRef, auth: AuthResult) -> Self {
Self {
pool,
schema_cache,
auth,
}
}
pub fn role(&self) -> &str {
&self.auth.role
}
pub fn claim(&self, key: &str) -> Option<&serde_json::Value> {
self.auth.claims.get(key)
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::collections::HashMap;
fn create_test_auth() -> AuthResult {
let mut claims = HashMap::new();
claims.insert("user_id".into(), serde_json::json!(123));
claims.insert("role".into(), serde_json::json!("admin"));
AuthResult {
role: "authenticated".into(),
claims,
}
}
#[test]
fn test_context_role() {
let auth = create_test_auth();
assert_eq!(auth.role, "authenticated");
}
#[test]
fn test_context_claim() {
let auth = create_test_auth();
assert_eq!(auth.claims.get("user_id"), Some(&serde_json::json!(123)));
}
}