All files / services gitlabClient.ts

100% Statements 23/23
83.33% Branches 10/12
100% Functions 1/1
100% Lines 23/23

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 6511x 11x 11x 11x 11x                     11x               17x 1x   16x   16x 16x   16x 4x 4x         3x     1x         16x 3x 3x           2x   1x     13x   16x      
import fs from 'fs';
import https from 'https';
import os from 'os';
import path from 'path';
import axios, { AxiosInstance } from 'axios';
 
/** Client for GitLab API using Axios */
export interface GitlabClientOptions {
  /** GitLab private token */
  token: string;
  /** GitLab base URL (e.g. https://gitlab.teleport.ftprod.fr/) */
  url?: string;
  workDir?: string;
}
 
export class GitlabClient {
  public readonly instance: AxiosInstance;
 
  constructor({
    token,
    url = 'https://gitlab.teleport.ftprod.fr/',
    workDir = os.homedir() + '/.ftprod-ai/tbot',
  }: GitlabClientOptions) {
    if (!token) {
      throw new Error('Le jeton GitLab est requis pour GitlabClient');
    }
    const baseURL = url.replace(/\/+$/, '') + '/api/v4';
    // Optionally load TLS client certs if present
    const certPath = path.join(workDir, 'dest', 'tls.crt');
    const keyPath = path.join(workDir, 'dest', 'tls.key');
    let httpsAgent: https.Agent | undefined;
    if (fs.existsSync(certPath) && fs.existsSync(keyPath)) {
      try {
        const agentOptions: https.AgentOptions = {
          rejectUnauthorized: false,
          cert: fs.readFileSync(certPath),
          key: fs.readFileSync(keyPath),
        };
        httpsAgent = new https.Agent(agentOptions);
      } catch {
        // ignore cert loading errors, fallback to no agent
        httpsAgent = undefined;
      }
    }
    // Create Axios instance; prefer a TLS-enabled instance if possible
    let instance: AxiosInstance;
    if (httpsAgent) {
      try {
        const created = axios.create({
          baseURL,
          headers: { 'PRIVATE-TOKEN': token },
          httpsAgent,
        });
        // Fallback to global axios if create() did not yield a usable instance
        instance = created && typeof created.get === 'function' ? created : axios;
      } catch {
        instance = axios;
      }
    } else {
      instance = axios;
    }
    this.instance = instance;
  }
}