All files / sdk/models triggers.ts

52% Statements 26/50
20.83% Branches 5/24
50% Functions 5/10
54.16% Lines 26/48

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 21210x 10x     10x   10x   10x 10x       10x 26x     26x   26x                         2x         2x 2x         2x                                           2x         2x 2x                 2x             1x         1x 1x           1x                 2x         2x 2x           2x                                                                                                                                                                                      
import { TriggerData, PusherUtils } from "../utils/pusher";
import logger from "../../utils/logger";
import { BackendClient } from "./backendClient";
 
import apiClient from "../client/client";
 
import { CEG } from "../utils/error";
import { ListTriggersData } from "../client";
import { TELEMETRY_LOGGER } from "../utils/telemetry";
import { TELEMETRY_EVENTS } from "../utils/telemetry/events";
 
type RequiredQuery = ListTriggersData["query"];
 
export class Triggers {
  trigger_to_client_event = "trigger_to_client";
 
  backendClient: BackendClient;
  fileName: string = "js/src/sdk/models/triggers.ts";
  constructor(backendClient: BackendClient) {
    this.backendClient = backendClient;
  }
 
  /**
   * Retrieves a list of all triggers in the Composio platform.
   *
   * This method allows you to fetch a list of all the available triggers. It supports pagination to handle large numbers of triggers. The response includes an array of trigger objects, each containing information such as the trigger's name, description, input parameters, expected response, associated app information, and enabled status.
   *
   * @param {ListTriggersData} data The data for the request.
   * @returns {CancelablePromise<ListTriggersResponse>} A promise that resolves to the list of all triggers.
   * @throws {ApiError} If the request fails.
   */
  async list(data: RequiredQuery = {}) {
    TELEMETRY_LOGGER.manualTelemetry(TELEMETRY_EVENTS.SDK_METHOD_INVOKED, {
      method: "list",
      file: this.fileName,
      params: { data },
    });
    try {
      const { data: response } = await apiClient.triggers.listTriggers({
        query: {
          appNames: data?.appNames,
        },
      });
      return response || [];
    } catch (error) {
      throw CEG.handleAllError(error);
    }
  }
 
  /**
   * Setup a trigger for a connected account.
   *
   * @param {SetupTriggerData} data The data for the request.
   * @returns {CancelablePromise<SetupTriggerResponse>} A promise that resolves to the setup trigger response.
   * @throws {ApiError} If the request fails.
   */
  async setup({
    connectedAccountId,
    triggerName,
    config,
  }: {
    connectedAccountId: string;
    triggerName: string;
    config: Record<string, any>;
  }): Promise<{ status: string; triggerId: string }> {
    TELEMETRY_LOGGER.manualTelemetry(TELEMETRY_EVENTS.SDK_METHOD_INVOKED, {
      method: "setup",
      file: this.fileName,
      params: { connectedAccountId, triggerName, config },
    });
    try {
      const response = await apiClient.triggers.enableTrigger({
        path: {
          connectedAccountId,
          triggerName,
        },
        body: {
          triggerConfig: config,
        },
      });
      return response.data as { status: string; triggerId: string };
    } catch (error) {
      throw CEG.handleAllError(error);
    }
  }
 
  async enable(data: { triggerId: string }) {
    TELEMETRY_LOGGER.manualTelemetry(TELEMETRY_EVENTS.SDK_METHOD_INVOKED, {
      method: "enable",
      file: this.fileName,
      params: { data },
    });
    try {
      const response = await apiClient.triggers.switchTriggerInstanceStatus({
        path: data,
        body: {
          enabled: true,
        },
      });
      return {
        status: "success",
      };
    } catch (error) {
      throw CEG.handleAllError(error);
    }
  }
 
  async disable(data: { triggerId: string }) {
    TELEMETRY_LOGGER.manualTelemetry(TELEMETRY_EVENTS.SDK_METHOD_INVOKED, {
      method: "disable",
      file: this.fileName,
      params: { data },
    });
    try {
      const response = await apiClient.triggers.switchTriggerInstanceStatus({
        path: data,
        body: {
          enabled: false,
        },
      });
      return {
        status: "success",
      };
    } catch (error) {
      throw CEG.handleAllError(error);
    }
  }
 
  async delete(data: { triggerInstanceId: string }) {
    TELEMETRY_LOGGER.manualTelemetry(TELEMETRY_EVENTS.SDK_METHOD_INVOKED, {
      method: "delete",
      file: this.fileName,
      params: { data },
    });
    try {
      const response = await apiClient.triggers.deleteTrigger({
        path: data,
      });
      return {
        status: "success",
      };
    } catch (error) {
      throw CEG.handleAllError(error);
    }
  }
 
  async subscribe(
    fn: (data: TriggerData) => void,
    filters: {
      appName?: string;
      triggerId?: string;
      connectionId?: string;
      integrationId?: string;
      triggerName?: string;
      triggerData?: string;
      entityId?: string;
    } = {}
  ) {
    TELEMETRY_LOGGER.manualTelemetry(TELEMETRY_EVENTS.SDK_METHOD_INVOKED, {
      method: "subscribe",
      file: this.fileName,
      params: { filters },
    });
    Iif (!fn) throw new Error("Function is required for trigger subscription");
    //@ts-ignore
    const clientId = await this.backendClient.getClientId();
    //@ts-ignore
    await PusherUtils.getPusherClient(
      this.backendClient.baseUrl,
      this.backendClient.apiKey
    );
 
    const shouldSendTrigger = (data: TriggerData) => {
      if (Object.keys(filters).length === 0) return true;
      else {
        return (
          (!filters.appName ||
            data.appName.toLowerCase() === filters.appName.toLowerCase()) &&
          (!filters.triggerId ||
            data.metadata.id.toLowerCase() ===
              filters.triggerId.toLowerCase()) &&
          (!filters.connectionId ||
            data.metadata.connectionId.toLowerCase() ===
              filters.connectionId.toLowerCase()) &&
          (!filters.triggerName ||
            data.metadata.triggerName.toLowerCase() ===
              filters.triggerName.toLowerCase()) &&
          (!filters.entityId ||
            data.metadata.connection.clientUniqueUserId.toLowerCase() ===
              filters.entityId.toLowerCase()) &&
          (!filters.integrationId ||
            data.metadata.connection.integrationId.toLowerCase() ===
              filters.integrationId.toLowerCase())
        );
      }
    };
 
    logger.debug("Subscribing to triggers", filters);
    PusherUtils.triggerSubscribe(clientId, (data: TriggerData) => {
      Iif (shouldSendTrigger(data)) {
        fn(data);
      }
    });
  }
 
  async unsubscribe() {
    //@ts-ignore
    const clientId = await this.backendClient.getClientId();
    PusherUtils.triggerUnsubscribe(clientId);
  }
}