2020-04-17 01:16:00 -05:00
|
|
|
#![deny(warnings)]
|
|
|
|
|
2020-06-30 10:13:15 -05:00
|
|
|
use std::pin::Pin;
|
|
|
|
|
2020-04-17 01:16:00 -05:00
|
|
|
use futures::{Stream, StreamExt};
|
2020-06-30 10:13:15 -05:00
|
|
|
use juniper::{
|
2020-11-06 20:15:18 -06:00
|
|
|
graphql_object, graphql_subscription, http::GraphQLRequest, DefaultScalarValue, EmptyMutation,
|
|
|
|
FieldError, RootNode, SubscriptionCoordinator,
|
2020-06-30 10:13:15 -05:00
|
|
|
};
|
2020-04-17 01:16:00 -05:00
|
|
|
use juniper_subscriptions::Coordinator;
|
|
|
|
|
|
|
|
#[derive(Clone)]
|
|
|
|
pub struct Database;
|
|
|
|
|
|
|
|
impl juniper::Context for Database {}
|
|
|
|
|
|
|
|
impl Database {
|
|
|
|
fn new() -> Self {
|
2022-07-13 05:30:51 -05:00
|
|
|
Self
|
2020-04-17 01:16:00 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
pub struct Query;
|
|
|
|
|
2020-11-06 20:15:18 -06:00
|
|
|
#[graphql_object(context = Database)]
|
2020-04-17 01:16:00 -05:00
|
|
|
impl Query {
|
2021-08-11 09:41:49 -05:00
|
|
|
fn hello_world() -> &'static str {
|
2020-04-17 01:16:00 -05:00
|
|
|
"Hello World!"
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
pub struct Subscription;
|
|
|
|
|
|
|
|
type StringStream = Pin<Box<dyn Stream<Item = Result<String, FieldError>> + Send>>;
|
|
|
|
|
2020-11-06 20:15:18 -06:00
|
|
|
#[graphql_subscription(context = Database)]
|
2020-04-17 01:16:00 -05:00
|
|
|
impl Subscription {
|
|
|
|
async fn hello_world() -> StringStream {
|
|
|
|
let stream =
|
2021-06-29 01:22:45 -05:00
|
|
|
futures::stream::iter(vec![Ok(String::from("Hello")), Ok(String::from("World!"))]);
|
2020-04-17 01:16:00 -05:00
|
|
|
Box::pin(stream)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
type Schema = RootNode<'static, Query, EmptyMutation<Database>, Subscription>;
|
|
|
|
|
|
|
|
fn schema() -> Schema {
|
2022-07-13 05:30:51 -05:00
|
|
|
Schema::new(Query, EmptyMutation::new(), Subscription)
|
2020-04-17 01:16:00 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
#[tokio::main]
|
|
|
|
async fn main() {
|
|
|
|
let schema = schema();
|
|
|
|
let coordinator = Coordinator::new(schema);
|
|
|
|
let req: GraphQLRequest<DefaultScalarValue> = serde_json::from_str(
|
2020-06-30 10:13:15 -05:00
|
|
|
r#"{
|
2020-04-17 01:16:00 -05:00
|
|
|
"query": "subscription { helloWorld }"
|
2020-06-30 10:13:15 -05:00
|
|
|
}"#,
|
2020-04-17 01:16:00 -05:00
|
|
|
)
|
2020-06-30 10:13:15 -05:00
|
|
|
.unwrap();
|
2020-04-17 01:16:00 -05:00
|
|
|
let ctx = Database::new();
|
|
|
|
let mut conn = coordinator.subscribe(&req, &ctx).await.unwrap();
|
|
|
|
while let Some(result) = conn.next().await {
|
|
|
|
println!("{}", serde_json::to_string(&result).unwrap());
|
|
|
|
}
|
|
|
|
}
|