@@ -5,7 +5,7 @@ use worker::*;
5
5
#[ shared_durable_object]
6
6
pub struct SharedCounter {
7
7
count : RefCell < usize > ,
8
- state : RefCell < State > ,
8
+ state : State ,
9
9
initialized : RefCell < bool > ,
10
10
env : Env ,
11
11
}
@@ -16,24 +16,22 @@ impl SharedDurableObject for SharedCounter {
16
16
Self {
17
17
count : RefCell :: new ( 0 ) ,
18
18
initialized : RefCell :: new ( false ) ,
19
- state : RefCell :: new ( state ) ,
19
+ state,
20
20
env,
21
21
}
22
22
}
23
23
24
24
async fn fetch ( & self , req : Request ) -> Result < Response > {
25
25
if !* self . initialized . borrow ( ) {
26
26
* self . initialized . borrow_mut ( ) = true ;
27
- let storage = self . state . borrow ( ) . storage ( ) ;
28
- let count = storage. get ( "count" ) . await . unwrap_or ( 0 ) ;
29
- * self . count . borrow_mut ( ) = count;
27
+ * self . count . borrow_mut ( ) = self . state . storage ( ) . get ( "count" ) . await . unwrap_or ( 0 ) ;
30
28
}
31
29
32
30
if req. path ( ) . eq ( "/ws" ) {
33
31
let pair = WebSocketPair :: new ( ) ?;
34
32
let server = pair. server ;
35
33
// accept websocket with hibernation api
36
- self . state . borrow ( ) . accept_web_socket ( & server) ;
34
+ self . state . accept_web_socket ( & server) ;
37
35
server
38
36
. serialize_attachment ( "hello" )
39
37
. expect ( "failed to serialize attachment" ) ;
@@ -48,9 +46,10 @@ impl SharedDurableObject for SharedCounter {
48
46
TimeoutFuture :: new ( 1_000 ) . await ;
49
47
50
48
* self . count . borrow_mut ( ) += 15 ;
51
- let mut storage = self . state . borrow ( ) . storage ( ) ;
52
- let count = * self . count . borrow ( ) ;
53
- storage. put ( "count" , count) . await ?;
49
+ self . state
50
+ . storage ( )
51
+ . put ( "count" , * self . count . borrow ( ) )
52
+ . await ?;
54
53
55
54
Response :: ok ( format ! (
56
55
"[durable_object]: self.count: {}, secret value: {}" ,
@@ -72,10 +71,9 @@ impl SharedDurableObject for SharedCounter {
72
71
TimeoutFuture :: new ( 1_000 ) . await ;
73
72
74
73
// get and increment storage by 15
75
- let mut storage = self . state . borrow ( ) . storage ( ) ;
76
- let mut count = storage. get ( "count" ) . await . unwrap_or ( 0 ) ;
74
+ let mut count = self . state . storage ( ) . get ( "count" ) . await . unwrap_or ( 0 ) ;
77
75
count += 15 ;
78
- storage. put ( "count" , count) . await ?;
76
+ self . state . storage ( ) . put ( "count" , count) . await ?;
79
77
// send value to client
80
78
ws. send_with_str ( format ! ( "{}" , count) )
81
79
. expect ( "failed to send value to client" ) ;
0 commit comments