All files / sdk/models backendClient.ts

93.75% Statements 15/16
85.71% Branches 6/7
100% Functions 3/3
93.75% Lines 15/16

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 7514x 14x         14x                                               19x 19x 19x   19x 2x       17x 1x     16x                 2x 1x     1x               16x                    
import apiClient from "../client/client"
import { client as axiosClient } from "../client/services.gen"
 
/**
 * Class representing the details required to initialize and configure the API client.
 */
export class BackendClient {
    /**
     * The API key used for authenticating requests.
     */
    public apiKey: string;
 
    /**
     * The base URL of the API against which requests will be made.
     */
    public baseUrl: string;
 
    /**
     * The runtime environment where the client is being used.
     */
    public runtime: string;
 
    /**
     * Creates an instance of apiClientDetails.
     * @param {string} apiKey - The API key for client initialization.
     * @param {string} baseUrl - The base URL for the API client.
     * @param {string} runtime - The runtime environment identifier.
     * @throws Will throw an error if the API key is not provided.
     */
    constructor(apiKey: string, baseUrl: string, runtime?: string) {
        this.runtime = runtime || '';
        this.apiKey = apiKey;
        this.baseUrl = baseUrl;
 
        if (!apiKey) {
            throw new Error(`API Key is required for initializing the client`);
        }
 
        // Validate baseUrl
        if (!baseUrl.startsWith("http://") && !baseUrl.startsWith("https://")) {
            throw new Error(`Base URL is not valid, got ${baseUrl}`);
        }
 
        this.initializeApiClient();
    }
 
    /**
     * Retrieves the client ID from the user's information.
     * @returns {Promise<string>} A promise that resolves to the client ID.
     * @throws Will throw an error if the HTTP request fails.
     */
    public async getClientId(): Promise<string> {
        const response = await apiClient.clientAuthService.getUserInfo();
        Iif (response.status !== 200) {
            throw new Error(`HTTP Error: ${response.status}`);
        }
        return (response.data as unknown as Record<string, Record<string, string>>).client.id;
    }
 
    /**
     * Initializes the API client with the provided configuration.
     * @private
     */
    private initializeApiClient() {
        axiosClient.setConfig({
            baseURL: this.baseUrl,
            headers: {
                'X-API-KEY': `${this.apiKey}`,
                'X-SOURCE': 'js_sdk',
                'X-RUNTIME': this.runtime
            }
        });
    }
}