Add `WSSubscription::start_with_initializer` and update examples.

This commit is contained in:
Sunli 2020-12-04 12:35:35 +08:00
parent 30dffdd47f
commit 6884b6e105
2 changed files with 16 additions and 13 deletions

@ -1 +1 @@
Subproject commit 71d7318ca5bd5f9b77ffc7136990c80db35a2b46
Subproject commit b51536fb0a933d25d9fcc91a08c2a53daf74daf8

View File

@ -41,6 +41,20 @@ where
) -> Result<HttpResponse, Error>
where
T: Stream<Item = Result<Bytes, PayloadError>> + 'static,
{
Self::start_with_initializer(schema, request, stream, |_| Ok(Default::default()))
}
/// Start an actor for subscription connection via websocket with an initialization function.
pub fn start_with_initializer<T, F>(
schema: Schema<Query, Mutation, Subscription>,
request: &HttpRequest,
stream: T,
initializer: F,
) -> Result<HttpResponse, Error>
where
T: Stream<Item = Result<Bytes, PayloadError>> + 'static,
F: FnOnce(serde_json::Value) -> Result<Data> + Send + Sync + 'static,
{
let protocol = match request
.headers()
@ -61,7 +75,7 @@ where
protocol,
last_heartbeat: Instant::now(),
messages: None,
initializer: None,
initializer: Some(Box::new(initializer)),
continuation: Vec::new(),
},
&["graphql-transport-ws", "graphql-ws"],
@ -70,17 +84,6 @@ where
)
}
/// Set a context data initialization function.
pub fn initializer<F>(self, f: F) -> Self
where
F: FnOnce(serde_json::Value) -> Result<Data> + Send + Sync + 'static,
{
Self {
initializer: Some(Box::new(f)),
..self
}
}
fn send_heartbeats(&self, ctx: &mut WebsocketContext<Self>) {
ctx.run_interval(HEARTBEAT_INTERVAL, |act, ctx| {
if Instant::now().duration_since(act.last_heartbeat) > CLIENT_TIMEOUT {