MCPcopy
hub / github.com/aspen-cloud/triplit / subscribe

Method subscribe

packages/client/src/sync-engine.ts:591–670  ·  view source on GitHub ↗

* @hidden

(
    params: CollectionQuery<any, any>,
    options: {
      onQueryFulfilled?: () => void;
      onQueryError?: ErrorCallback;
      onQuerySyncStateChange?: SyncStateCallback;
    } = {}
  )

Source from the content-addressed store, hash-verified

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);

Callers 1

syncQueryMethod · 0.95

Calls 7

connectQueryMethod · 0.95
disconnectQueryMethod · 0.95
hashQueryFunction · 0.90
hasMethod · 0.80
setMethod · 0.65
getMethod · 0.65
deleteMethod · 0.65

Tested by

no test coverage detected