Last active
November 25, 2024 12:19
-
-
Save obmarg/a02bd33f72b33d8f2e684f8094807760 to your computer and use it in GitHub Desktop.
A single file schema first rust graphql server
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env cargo | |
//! ```cargo | |
//! [dependencies] | |
//! futures = "0.3" | |
//! graphql-mocks = { git = "https://github.com/grafbase/grafbase.git", rev = "e23190a" } | |
//! serde_json = "1" | |
//! tokio = { version = "1", features = ["rt-multi-thread", "macros"] } | |
//! ``` | |
use graphql_mocks::{ | |
dynamic::{DynamicSchema, ResolverContext}, | |
MockGraphQlServer, | |
}; | |
use serde_json::json; | |
#[tokio::main] | |
async fn main() { | |
let server = MockGraphQlServer::new( | |
DynamicSchema::builder( | |
r#" | |
type Query { | |
products(first: Int, after: String): ProductConnection @listSize( | |
slicingArguments: ["first"] | |
sizedFields: ["edges"] | |
) | |
} | |
type ProductConnection { | |
edges: [ProductEdge] | |
totalSize: Int! @cost(weight: 50) | |
} | |
type ProductEdge { | |
node: Product, | |
cursor: String | |
} | |
type Product { | |
id: ID! | |
} | |
"#, | |
) | |
.with_resolver("Query", "products", |context: ResolverContext<'_>| { | |
let first = context.args.get("first").unwrap(); | |
let num = first.deserialize::<usize>().unwrap(); | |
let edges = std::iter::repeat(()) | |
.enumerate() | |
.map(|(i, _)| { | |
let cursor = format!("cursor_{i}"); | |
json!({ | |
"node": {"id": i}, | |
"cursor": cursor, | |
}) | |
}) | |
.take(num) | |
.collect::<Vec<_>>(); | |
Some(json!({ | |
"edges": edges, | |
"totalSize": 10000 | |
})) | |
}) | |
.finish(), | |
) | |
.await; | |
println!("Server running on {}", server.port()); | |
futures::future::pending::<()>().await; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment