Skip to main content

sz_orm_core/
graphql_adapter.rs

1//! # GraphQL Adapter — sz-orm-core GraphQL 适配层
2//!
3//! v5.0.0 M4:将 sz-orm-graphql 的 GraphQLServer 接入 sz-orm-core,
4//! 提供 `graphql_execute` / `graphql_query_count` 入口。
5
6use std::sync::atomic::{AtomicU64, Ordering};
7use std::sync::OnceLock;
8
9use parking_lot::RwLock;
10use sz_orm_graphql::{GraphQLSchema, GraphQLServer};
11
12static GRAPHQL_SERVER: OnceLock<RwLock<GraphQLServer>> = OnceLock::new();
13static QUERY_COUNT: AtomicU64 = AtomicU64::new(0);
14
15fn server() -> &'static RwLock<GraphQLServer> {
16    GRAPHQL_SERVER.get_or_init(|| {
17        let schema = GraphQLSchema::new();
18        RwLock::new(GraphQLServer::new(8080).with_schema(schema))
19    })
20}
21
22/// 执行 GraphQL 查询
23pub fn graphql_execute(query: &str) -> Result<serde_json::Value, String> {
24    QUERY_COUNT.fetch_add(1, Ordering::Relaxed);
25    let server = server().read();
26    server.execute_query(query)
27}
28
29/// 获取查询计数
30pub fn graphql_query_count() -> u64 {
31    QUERY_COUNT.load(Ordering::Relaxed)
32}
33
34#[cfg(test)]
35mod tests {
36    use super::*;
37
38    #[test]
39    fn test_graphql_execute_is_reachable() {
40        let result = graphql_execute("{ __typename }");
41        assert!(
42            result.is_ok() || result.is_err(),
43            "graphql_execute should be callable"
44        );
45    }
46
47    #[test]
48    fn test_graphql_count_increments() {
49        let before = graphql_query_count();
50        let _ = graphql_execute("{ __typename }");
51        let after = graphql_query_count();
52        assert!(after > before);
53    }
54}