All files / src/sdk/models connectedAccounts.ts

38.46% Statements 30/78
54.16% Branches 26/48
38.46% Functions 5/13
40% Lines 30/75

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 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367                12x 12x               12x 12x 12x                                                             12x   31x             31x 31x                     17x         17x 17x 17x 17x             17x                           14x         14x 14x 14x         14x                                                                                                                                                                                               2x         2x 2x                                                 2x   2x                                                                                                 12x                               2x 2x 2x 2x                                                                                                                  
import { Client } from "@hey-api/client-axios";
import { z } from "zod";
import {
  ConnectedAccountResponseDTO,
  ConnectionParams,
  DeleteRowAPIDTO,
  GetConnectionsResponseDto,
} from "../client";
import { default as apiClient } from "../client/client";
import {
  ZInitiateConnectionDataReq,
  ZListConnectionsData,
  ZReinitiateConnectionPayloadDto,
  ZSaveUserAccessDataParam,
  ZSingleConnectionParams,
} from "../types/connectedAccount";
import { ZAuthMode } from "../types/integration";
import { CEG } from "../utils/error";
import { TELEMETRY_LOGGER } from "../utils/telemetry";
import { TELEMETRY_EVENTS } from "../utils/telemetry/events";
import { AxiosBackendClient } from "./backendClient";
 
type ConnectedAccountsListData = z.infer<typeof ZListConnectionsData> & {
  /** @deprecated use appUniqueKeys field instead */
  appNames?: string;
};
 
type InitiateConnectionDataReq = z.infer<typeof ZInitiateConnectionDataReq>;
 
type SingleConnectionParam = z.infer<typeof ZSingleConnectionParams>;
 
type SaveUserAccessDataParam = z.infer<typeof ZSaveUserAccessDataParam>;
 
type ReinitiateConnectionPayload = z.infer<
  typeof ZReinitiateConnectionPayloadDto
>;
 
export type ConnectedAccountListResponse = GetConnectionsResponseDto;
export type SingleConnectedAccountResponse = ConnectedAccountResponseDTO;
export type SingleDeleteResponse = DeleteRowAPIDTO;
 
export type ConnectionChangeResponse = {
  status: "success";
  connectedAccountId: string;
};
export type ConnectionItem = ConnectionParams;
 
/**
 * Class representing connected accounts in the system.
 */
export class ConnectedAccounts {
  private backendClient: AxiosBackendClient;
  private fileName: string = "js/src/sdk/models/connectedAccounts.ts";
  private client: Client;
  /**
   * Initializes a new instance of the ConnectedAccounts class.
   * @param {AxiosBackendClient} backendClient - The backend client instance.
   */
  constructor(backendClient: AxiosBackendClient, client: Client) {
    this.backendClient = backendClient;
    this.client = client;
  }
 
  /**
   * List all connected accounts
   * @param {ConnectedAccountsListData} data - The data for the connected accounts list
   * @returns {Promise<ConnectedAccountListResponse>} - A promise that resolves to a list of connected accounts
   */
  async list(
    data: ConnectedAccountsListData
  ): Promise<ConnectedAccountListResponse> {
    TELEMETRY_LOGGER.manualTelemetry(TELEMETRY_EVENTS.SDK_METHOD_INVOKED, {
      method: "list",
      file: this.fileName,
      params: { data },
    });
    try {
      const { appNames, appUniqueKeys } = ZListConnectionsData.parse(data);
      const finalAppNames = appNames || appUniqueKeys?.join(",");
      const res = await apiClient.connections.listConnections({
        client: this.client,
        query: {
          ...data,
          appNames: finalAppNames,
        },
      });
      return res.data!;
    } catch (error) {
      throw CEG.handleAllError(error);
    }
  }
 
  /**
   * Get a single connected account
   * @param {SingleConnectionParam} data - The data for the single connection
   * @returns {Promise<SingleConnectedAccountResponse>} - A promise that resolves to a single connected account
   */
  async get(
    data: SingleConnectionParam
  ): Promise<SingleConnectedAccountResponse> {
    TELEMETRY_LOGGER.manualTelemetry(TELEMETRY_EVENTS.SDK_METHOD_INVOKED, {
      method: "get",
      file: this.fileName,
      params: { data },
    });
    try {
      ZSingleConnectionParams.parse(data);
      const res = await apiClient.connections.getConnection({
        client: this.client,
        path: data,
        throwOnError: true,
      });
      return res.data;
    } catch (error) {
      throw CEG.handleAllError(error);
    }
  }
 
  /**
   * Delete a single connected account
   * @param {SingleConnectionParam} data - The data for the single connection
   * @returns {Promise<SingleDeleteResponse>} - A promise that resolves when the connected account is deleted
   */
  async delete(data: SingleConnectionParam): Promise<SingleDeleteResponse> {
    TELEMETRY_LOGGER.manualTelemetry(TELEMETRY_EVENTS.SDK_METHOD_INVOKED, {
      method: "delete",
      file: this.fileName,
      params: { data },
    });
    try {
      ZSingleConnectionParams.parse(data);
      const res = await apiClient.connections.deleteConnection({
        client: this.client,
        path: data,
        throwOnError: true,
      });
      return res.data!;
    } catch (error) {
      throw CEG.handleAllError(error);
    }
  }
 
  /**
   * Disable a single connected account
   * @param {SingleConnectionParam} data - The data for the single connection
   * @returns {Promise<ConnectionChangeResponse>} - A promise that resolves when the connected account is disabled
   */
  async disable(
    data: SingleConnectionParam
  ): Promise<ConnectionChangeResponse> {
    TELEMETRY_LOGGER.manualTelemetry(TELEMETRY_EVENTS.SDK_METHOD_INVOKED, {
      method: "disable",
      file: this.fileName,
      params: { data },
    });
    try {
      ZSingleConnectionParams.parse(data);
      const res = await apiClient.connections.disableConnection({
        client: this.client,
        path: data,
        throwOnError: true,
      });
      return {
        status: "success",
        connectedAccountId: data.connectedAccountId,
      };
    } catch (error) {
      throw CEG.handleAllError(error);
    }
  }
 
  /**
   * Enable a single connected account
   * @param {SingleConnectionParam} data - The data for the single connection
   * @returns {Promise<ConnectionChangeResponse>} - A promise that resolves when the connected account is enabled
   */
  async enable(data: SingleConnectionParam): Promise<ConnectionChangeResponse> {
    TELEMETRY_LOGGER.manualTelemetry(TELEMETRY_EVENTS.SDK_METHOD_INVOKED, {
      method: "enable",
      file: this.fileName,
      params: { data },
    });
    try {
      ZSingleConnectionParams.parse(data);
      await apiClient.connections.enableConnection({
        client: this.client,
        path: {
          connectedAccountId: data.connectedAccountId,
        },
        throwOnError: true,
      });
      return {
        status: "success",
        connectedAccountId: data.connectedAccountId,
      };
    } catch (error) {
      throw CEG.handleAllError(error);
    }
  }
 
  /**
   * Initiate a connection
   * @param {InitiateConnectionDataReq} payload - The payload for the connection initiation
   * @returns {Promise<ConnectionRequest>} - A promise that resolves to a connection request
   */
  async initiate(
    payload: InitiateConnectionDataReq
  ): Promise<ConnectionRequest> {
    TELEMETRY_LOGGER.manualTelemetry(TELEMETRY_EVENTS.SDK_METHOD_INVOKED, {
      method: "initiate",
      file: this.fileName,
      params: { payload },
    });
    try {
      const connection = await apiClient.connectionsV2.initiateConnectionV2({
        client: this.client,
        body: {
          app: {
            uniqueKey: payload.appName!,
            integrationId: payload.integrationId,
          },
          config: {
            name: payload.appName!,
            useComposioAuth: !!payload.authMode && !!payload.authConfig,
            authScheme: payload.authMode as z.infer<typeof ZAuthMode>,
            integrationSecrets: payload.authConfig,
          },
          connection: {
            entityId: payload.entityId,
            initiateData:
              (payload.connectionParams as Record<string, unknown>) || {},
            extra: {
              redirectURL: payload.redirectUri,
              labels: payload.labels || [],
            },
          },
        },
      });
 
      const connectionResponse = connection?.data?.connectionResponse;
 
      return new ConnectionRequest({
        connectionStatus: connectionResponse?.connectionStatus!,
        connectedAccountId: connectionResponse?.connectedAccountId!,
        redirectUri: connectionResponse?.redirectUrl!,
        client: this.client,
      });
    } catch (error) {
      throw CEG.handleAllError(error);
    }
  }
 
  /**
   * Reinitiate a connection
   * @param {ReinitiateConnectionPayload} data - The payload for the connection reinitialization
   * @returns {Promise<ConnectionRequest>} - A promise that resolves to a connection request
   */
  async reinitiateConnection(data: ReinitiateConnectionPayload) {
    TELEMETRY_LOGGER.manualTelemetry(TELEMETRY_EVENTS.SDK_METHOD_INVOKED, {
      method: "reinitiateConnection",
      file: this.fileName,
      params: { data },
    });
    try {
      ZReinitiateConnectionPayloadDto.parse(data);
      const connection = await apiClient.connections.reinitiateConnection({
        client: this.client,
        path: {
          connectedAccountId: data.connectedAccountId,
        },
        body: {
          data: data.data,
          redirectUri: data.redirectUri,
        },
      });
 
      const res = connection.data;
 
      return new ConnectionRequest({
        connectionStatus: res?.connectionStatus!,
        connectedAccountId: res?.connectedAccountId!,
        redirectUri: res?.redirectUrl!,
        client: this.client,
      });
    } catch (error) {
      throw CEG.handleAllError(error);
    }
  }
}
 
export class ConnectionRequest {
  connectionStatus: string;
  connectedAccountId: string;
  redirectUrl: string | null;
  private client: Client;
  constructor({
    connectionStatus,
    connectedAccountId,
    redirectUri,
    client,
  }: {
    connectionStatus: string;
    connectedAccountId: string;
    redirectUri: string | null;
    client: Client;
  }) {
    this.connectionStatus = connectionStatus;
    this.connectedAccountId = connectedAccountId;
    this.redirectUrl = redirectUri;
    this.client = client;
  }
 
  async saveUserAccessData(data: SaveUserAccessDataParam) {
    try {
      ZSaveUserAccessDataParam.parse(data);
      const { data: connectedAccount } =
        await apiClient.connections.getConnection({
          client: this.client,
          path: { connectedAccountId: this.connectedAccountId },
        });
      Iif (!connectedAccount) throw new Error("Connected account not found");
      return await apiClient.connections.initiateConnection({
        client: this.client,
        body: {
          integrationId: connectedAccount.integrationId,
          //@ts-ignore
          data: data.fieldInputs,
          redirectUri: data.redirectUrl,
          userUuid: data.entityId,
          entityId: data.entityId,
        },
      });
    } catch (error) {
      throw CEG.handleAllError(error);
    }
  }
 
  /**
   * Wait until the connection becomes active
   * @param {number} timeout - The timeout for the connection to become active
   * @returns {Promise<Connection>} - A promise that resolves to the connection
   */
  async waitUntilActive(timeout = 60) {
    try {
      const startTime = Date.now();
      while (Date.now() - startTime < timeout * 1000) {
        const connection = await apiClient.connections
          .getConnection({
            client: this.client,
            path: { connectedAccountId: this.connectedAccountId },
          })
          .then((res) => res.data);
        Iif (!connection) throw new Error("Connected account not found");
        Iif (connection.status === "ACTIVE") {
          return connection;
        }
        await new Promise((resolve) => setTimeout(resolve, 1000));
      }
      throw new Error(
        "Connection did not become active within the timeout period."
      );
    } catch (error) {
      throw CEG.handleAllError(error);
    }
  }
}