@@ -4,6 +4,16 @@ const Promise = require('./promise');
4
4
const { inherits } = require ( './utils' ) ;
5
5
const { request } = require ( './request' ) ;
6
6
7
+ const subscribe = ( queryJSON , subscriptionId ) =>
8
+ request ( {
9
+ method : 'POST' ,
10
+ path : '/LiveQuery/subscribe' ,
11
+ data : {
12
+ query : queryJSON ,
13
+ id : subscriptionId ,
14
+ } ,
15
+ } ) ;
16
+
7
17
module . exports = AV => {
8
18
/**
9
19
* @class
@@ -13,12 +23,19 @@ module.exports = AV => {
13
23
AV . LiveQuery = inherits (
14
24
EventEmitter ,
15
25
/** @lends AV.LiveQuery.prototype */ {
16
- constructor ( id , client ) {
26
+ constructor ( id , client , queryJSON , subscriptionId ) {
17
27
EventEmitter . apply ( this ) ;
18
28
this . id = id ;
19
29
this . _client = client ;
20
30
this . _client . register ( this ) ;
31
+ this . _queryJSON = queryJSON ;
32
+ this . _subscriptionId = subscriptionId ;
21
33
client . on ( 'message' , this . _dispatch . bind ( this ) ) ;
34
+ client . on ( 'reconnect' , ( ) => {
35
+ subscribe ( this . _queryJSON , this . _subscriptionId ) . catch ( error =>
36
+ console . error ( `LiveQuery resubscribe error: ${ error . message } ` )
37
+ ) ;
38
+ } ) ;
22
39
} ,
23
40
_dispatch ( message ) {
24
41
message . forEach ( ( { op, object, query_id : queryId , updatedKeys } ) => {
@@ -96,28 +113,27 @@ module.exports = AV => {
96
113
) ;
97
114
if ( ! ( query instanceof AV . Query ) )
98
115
throw new TypeError ( 'LiveQuery must be inited with a Query' ) ;
99
- const { where, keys, returnACL } = query . toJSON ( ) ;
100
116
return Promise . resolve ( userDefinedSubscriptionId ) . then ( subscriptionId =>
101
117
AV . _config . realtime
102
118
. createLiveQueryClient ( subscriptionId )
103
- . then ( liveQueryClient =>
104
- request ( {
105
- method : 'POST' ,
106
- path : '/LiveQuery/subscribe' ,
107
- data : {
108
- query : {
109
- where,
110
- keys,
111
- returnACL,
112
- className : query . className ,
113
- } ,
114
- id : subscriptionId ,
115
- } ,
116
- } ) . then (
119
+ . then ( liveQueryClient => {
120
+ const { where, keys, returnACL } = query . toJSON ( ) ;
121
+ const queryJSON = {
122
+ where,
123
+ keys,
124
+ returnACL,
125
+ className : query . className ,
126
+ } ;
127
+ return subscribe ( queryJSON , subscriptionId ) . then (
117
128
( { query_id : queryId } ) =>
118
- new AV . LiveQuery ( queryId , liveQueryClient )
119
- )
120
- )
129
+ new AV . LiveQuery (
130
+ queryId ,
131
+ liveQueryClient ,
132
+ queryJSON ,
133
+ subscriptionId
134
+ )
135
+ ) ;
136
+ } )
121
137
) ;
122
138
} ,
123
139
}
0 commit comments