11use std:: { env, pin:: Pin , time:: Duration } ;
22
33use actix_cors:: Cors ;
4- use actix_web:: { middleware, web, App , Error , HttpRequest , HttpResponse , HttpServer } ;
4+ use actix_web:: { http :: header , middleware, web, App , Error , HttpRequest , HttpResponse , HttpServer } ;
55
66use juniper:: {
77 graphql_object, graphql_subscription,
@@ -64,27 +64,29 @@ impl Subscription {
6464
6565 use rand:: { rngs:: StdRng , Rng , SeedableRng } ;
6666 let mut rng = StdRng :: from_entropy ( ) ;
67-
68- let stream = tokio :: time :: interval ( Duration :: from_secs ( 3 ) ) . map ( move |_| {
67+ let mut interval = tokio :: time :: interval ( Duration :: from_secs ( 5 ) ) ;
68+ let stream = async_stream :: stream! {
6969 counter += 1 ;
70-
71- if counter == 2 {
72- Err ( FieldError :: new (
73- "some field error from handler" ,
74- Value :: Scalar ( DefaultScalarValue :: String (
75- "some additional string" . to_string ( ) ,
76- ) ) ,
77- ) )
78- } else {
79- let random_id = rng. gen_range ( 1000 , 1005 ) . to_string ( ) ;
80- let human = context. get_human ( & random_id) . unwrap ( ) . clone ( ) ;
81-
82- Ok ( RandomHuman {
83- id : human. id ( ) . to_owned ( ) ,
84- name : human. name ( ) . unwrap ( ) . to_owned ( ) ,
85- } )
70+ loop {
71+ interval. tick( ) . await ;
72+ if counter == 2 {
73+ yield Err ( FieldError :: new(
74+ "some field error from handler" ,
75+ Value :: Scalar ( DefaultScalarValue :: String (
76+ "some additional string" . to_string( ) ,
77+ ) ) ,
78+ ) )
79+ } else {
80+ let random_id = rng. gen_range( 1000 ..1005 ) . to_string( ) ;
81+ let human = context. get_human( & random_id) . unwrap( ) . clone( ) ;
82+
83+ yield Ok ( RandomHuman {
84+ id: human. id( ) . to_owned( ) ,
85+ name: human. name( ) . unwrap( ) . to_owned( ) ,
86+ } )
87+ }
8688 }
87- } ) ;
89+ } ;
8890
8991 Box :: pin ( stream)
9092 }
@@ -117,7 +119,10 @@ async fn main() -> std::io::Result<()> {
117119 . wrap ( middleware:: Logger :: default ( ) )
118120 . wrap (
119121 Cors :: default ( )
122+ . allowed_origin ( "http://127.0.0.1:8080" )
120123 . allowed_methods ( vec ! [ "POST" , "GET" ] )
124+ . allowed_headers ( vec ! [ header:: AUTHORIZATION , header:: ACCEPT ] )
125+ . allowed_header ( header:: CONTENT_TYPE )
121126 . supports_credentials ( )
122127 . max_age ( 3600 ) ,
123128 )
@@ -130,7 +135,7 @@ async fn main() -> std::io::Result<()> {
130135 . service ( web:: resource ( "/playground" ) . route ( web:: get ( ) . to ( playground) ) )
131136 . default_service ( web:: route ( ) . to ( || {
132137 HttpResponse :: Found ( )
133- . header ( "location" , "/playground" )
138+ . append_header ( ( header :: LOCATION , "/playground" ) )
134139 . finish ( )
135140 } ) )
136141 } )
0 commit comments