* @hidden
(
params: CollectionQuery<any, any>,
options: {
onQueryFulfilled?: () => void;
onQueryError?: ErrorCallback;
onQuerySyncStateChange?: SyncStateCallback;
} = {}
)
| 589 | * @hidden |
| 590 | */ |
| 591 | async subscribe( |
| 592 | params: CollectionQuery<any, any>, |
| 593 | options: { |
| 594 | onQueryFulfilled?: () => void; |
| 595 | onQueryError?: ErrorCallback; |
| 596 | onQuerySyncStateChange?: SyncStateCallback; |
| 597 | } = {} |
| 598 | ) { |
| 599 | const { onQueryFulfilled, onQueryError, onQuerySyncStateChange } = options; |
| 600 | const id = hashQuery(params); |
| 601 | const queryHasMounted = this.queries.has(id); |
| 602 | if (!queryHasMounted) { |
| 603 | this.queries.set(id, { |
| 604 | params, |
| 605 | syncState: 'NOT_STARTED', |
| 606 | syncStateCallbacks: new Set(), |
| 607 | subCount: 0, |
| 608 | hasSent: false, |
| 609 | abortController: new AbortController(), |
| 610 | }); |
| 611 | } |
| 612 | // Safely using query! here because we just set it |
| 613 | const query = this.queries.get(id)!; |
| 614 | query.subCount++; |
| 615 | |
| 616 | if (onQuerySyncStateChange) { |
| 617 | query.syncStateCallbacks.add(onQuerySyncStateChange); |
| 618 | } |
| 619 | let fulfillmentCallback: SyncStateCallback | undefined = undefined; |
| 620 | |
| 621 | if (onQueryFulfilled) { |
| 622 | query.syncState === 'FULFILLED' && onQueryFulfilled(); |
| 623 | fulfillmentCallback = (state) => { |
| 624 | if (state === 'FULFILLED') { |
| 625 | onQueryFulfilled(); |
| 626 | } |
| 627 | }; |
| 628 | query.syncStateCallbacks.add(fulfillmentCallback); |
| 629 | } |
| 630 | let errorCallback: SyncStateCallback | undefined = undefined; |
| 631 | if (onQueryError) { |
| 632 | errorCallback = (state, error) => { |
| 633 | if (state === 'ERROR') { |
| 634 | onQueryError(error); |
| 635 | } |
| 636 | }; |
| 637 | query.syncStateCallbacks.add(errorCallback); |
| 638 | } |
| 639 | if (!queryHasMounted) { |
| 640 | await this.connectQuery(id); |
| 641 | } |
| 642 | |
| 643 | return () => { |
| 644 | const query = this.queries.get(id); |
| 645 | // If we cannot find the query, we may have already disconnected or reset our state |
| 646 | // just in case send a disconnect signal to the server |
| 647 | if (!query) { |
| 648 | this.disconnectQuery(id); |
no test coverage detected