All files / sdk/models connectedAccounts.ts

34.24% Statements 25/73
34.37% Branches 11/32
42.85% Functions 6/14
35.71% Lines 25/70

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                12x 12x   12x 12x 12x                                   12x           30x 30x 30x           15x 15x 15x                                             14x 14x 14x                                                         2x                   2x   2x                                                     2x                   2x   2x                     12x                           2x 2x 2x                                                                                                                              
import {
  InitiateConnectionPayloadDto,
  GetConnectionsResponseDto,
  GetConnectionInfoData,
  GetConnectionInfoResponse,
  GetConnectionsData,
  InitiateConnectionResponse2,
} from "../client";
import client from "../client/client";
import apiClient from "../client/client";
import { BackendClient } from "./backendClient";
import { Integrations } from "./integrations";
import { Apps } from "./apps";
import { CEG } from "../utils/error";
import { SDK_ERROR_CODES } from "../utils/errors/src/constants";
 
type ConnectedAccountsListData = GetConnectionsData["query"] & {
  appNames?: string;
};
 
type InitiateConnectionDataReq = InitiateConnectionPayloadDto & {
  data?: Record<string, unknown> | unknown;
  entityId?: string;
  labels?: string[];
  integrationId?: string;
  redirectUri?: string;
  authMode?: string;
  authConfig?: { [key: string]: any };
  appName?: string;
};
 
export class ConnectedAccounts {
  backendClient: BackendClient;
  integrations: Integrations;
  apps: Apps;
 
  constructor(backendClient: BackendClient) {
    this.backendClient = backendClient;
    this.integrations = new Integrations(this.backendClient);
    this.apps = new Apps(this.backendClient);
  }
 
  async list(
    data: ConnectedAccountsListData
  ): Promise<GetConnectionsResponseDto> {
    try {
      const res = await apiClient.connections.getConnections({ query: data });
      return res.data!;
    } catch (error) {
      throw CEG.handleAllError(error);
    }
  }
 
  async create(data: InitiateConnectionPayloadDto) {
    try {
      const { data: res } = (await apiClient.connections.initiateConnection({
        body: data,
      })) as { data: InitiateConnectionResponse2 };
 
      return new ConnectionRequest({
        connectionStatus: res.connectionStatus,
        connectedAccountId: res.connectedAccountId,
        redirectUri: res.redirectUrl ?? null,
      });
    } catch (error) {
      throw CEG.handleAllError(error);
    }
  }
 
  async get(data: { connectedAccountId: string }) {
    try {
      const res = await apiClient.connections.getConnection({ path: data });
      return res.data;
    } catch (error) {
      throw CEG.handleAllError(error);
    }
  }
 
  async delete(data: { connectedAccountId: string }) {
    try {
      const res = await apiClient.connections.deleteConnection({ path: data });
      return res.data;
    } catch (error) {
      throw CEG.handleAllError(error);
    }
  }
 
  async getAuthParams(data: { connectedAccountId: string }) {
    try {
      const res = await apiClient.connections.getConnection({
        path: { connectedAccountId: data.connectedAccountId },
      });
      return res.data;
    } catch (error) {
      throw CEG.handleAllError(error);
    }
  }
 
  async initiate(
    payload: InitiateConnectionDataReq
  ): Promise<ConnectionRequest> {
    try {
      let {
        integrationId,
        entityId = "default",
        labels,
        data = {},
        redirectUri,
        authMode,
        authConfig,
        appName,
      } = payload;
 
      Iif (!integrationId && authMode) {
        const timestamp = new Date().toISOString().replace(/[-:.]/g, "");
 
        Iif (!appName)
          throw new Error(
            "appName is required when integrationId is not provided"
          );
        Iif (!authMode)
          throw new Error(
            "authMode is required when integrationId is not provided"
          );
        Iif (!authConfig)
          throw new Error(
            "authConfig is required when integrationId is not provided"
          );
 
        const app = await this.apps.get({ appKey: appName });
        const integration = await this.integrations.create({
          appId: app.appId!,
          name: `integration_${timestamp}`,
          authScheme: authMode,
          authConfig: authConfig,
          useComposioAuth: false,
        });
        integrationId = integration?.id!;
      }
 
      const res = await client.connections
        .initiateConnection({
          body: {
            integrationId,
            entityId,
            labels,
            redirectUri,
            data,
          },
        })
        .then((res) => res.data);
 
      return new ConnectionRequest({
        connectionStatus: res?.connectionStatus!,
        connectedAccountId: res?.connectedAccountId!,
        redirectUri: res?.redirectUrl!,
      });
    } catch (error) {
      throw CEG.handleAllError(error);
    }
  }
}
 
export class ConnectionRequest {
  connectionStatus: string;
  connectedAccountId: string;
  redirectUrl: string | null;
 
  constructor({
    connectionStatus,
    connectedAccountId,
    redirectUri,
  }: {
    connectionStatus: string;
    connectedAccountId: string;
    redirectUri: string | null;
  }) {
    this.connectionStatus = connectionStatus;
    this.connectedAccountId = connectedAccountId;
    this.redirectUrl = redirectUri;
  }
 
  async saveUserAccessData(data: {
    fieldInputs: Record<string, string>;
    redirectUrl?: string;
    entityId?: string;
  }) {
    try {
      const { data: connectedAccount } =
        await apiClient.connections.getConnection({
          path: { connectedAccountId: this.connectedAccountId },
        });
      Iif (!connectedAccount) throw new Error("Connected account not found");
      return await apiClient.connections.initiateConnection({
        body: {
          integrationId: connectedAccount.integrationId,
          //@ts-ignore
          data: data.fieldInputs,
          redirectUri: data.redirectUrl,
          userUuid: data.entityId,
          entityId: data.entityId,
        },
      });
    } catch (error) {
      throw CEG.handleAllError(error);
    }
  }
 
  async getAuthInfo(
    data: GetConnectionInfoData["path"]
  ): Promise<GetConnectionInfoResponse> {
    try {
      const res = await client.connections.getConnectionInfo({ path: data });
      return res.data!;
    } catch (error) {
      throw CEG.handleAllError(error);
    }
  }
 
  async waitUntilActive(timeout = 60) {
    try {
      const startTime = Date.now();
      while (Date.now() - startTime < timeout * 1000) {
        const connection = await apiClient.connections
          .getConnection({
            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);
    }
  }
}