@@ -4,6 +4,16 @@ const Promise = require('./promise');
44const { inherits } = require ( './utils' ) ;
55const { request } = require ( './request' ) ;
66
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+
717module . exports = AV => {
818 /**
919 * @class
@@ -13,12 +23,19 @@ module.exports = AV => {
1323 AV . LiveQuery = inherits (
1424 EventEmitter ,
1525 /** @lends AV.LiveQuery.prototype */ {
16- constructor ( id , client ) {
26+ constructor ( id , client , queryJSON , subscriptionId ) {
1727 EventEmitter . apply ( this ) ;
1828 this . id = id ;
1929 this . _client = client ;
2030 this . _client . register ( this ) ;
31+ this . _queryJSON = queryJSON ;
32+ this . _subscriptionId = subscriptionId ;
2133 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+ } ) ;
2239 } ,
2340 _dispatch ( message ) {
2441 message . forEach ( ( { op, object, query_id : queryId , updatedKeys } ) => {
@@ -96,28 +113,27 @@ module.exports = AV => {
96113 ) ;
97114 if ( ! ( query instanceof AV . Query ) )
98115 throw new TypeError ( 'LiveQuery must be inited with a Query' ) ;
99- const { where, keys, returnACL } = query . toJSON ( ) ;
100116 return Promise . resolve ( userDefinedSubscriptionId ) . then ( subscriptionId =>
101117 AV . _config . realtime
102118 . 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 (
117128 ( { 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+ } )
121137 ) ;
122138 } ,
123139 }
0 commit comments