All files / src/controllers UtilsController.ts

97.3% Statements 36/37
70.59% Branches 12/17
100% Functions 6/6
97.3% Lines 36/37

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  5x 5x           5x 5x 5x           5x 10x     10x                 10x 1x             10x 3x 3x 3x                   10x       5x 5x 5x 1x     4x   4x 4x 1x     3x     3x 3x 3x     3x 3x                       3x               3x 1x 1x     2x       2x 2x      
import { Id } from '../types/CommonTypes';
import { WellKnownConfigurationKeys } from '../types/ConfigurationTypes';
import {
    FilePointer,
    UploadAssetValidationError,
    UploadAssetValidationErrorType,
    UploadValidationConfiguration,
} from '../types/ConnectorTypes';
import { getEditorResponseData } from '../utils/EditorResponseData';
import { EnvironmentType } from '../utils/Enums';
import { round } from '../utils/MathUtils';
 
/**
 * The UtilsController exposes a set of useful utilities that can be used to make some repeated tasks a bit easier
 * Methods inside this controller can be called by `window.SDK.utils.{method-name}`
 */
export class UtilsController {
    #localConfig: Map<string, string>;
 
    constructor(localConfig: Map<string, string>) {
        this.#localConfig = localConfig;
    }
 
    /**
     * This method can round a value to a certain precision, default is 2
     * @param val the value that needs to be rounded
     * @param precision the precision of the rounding operation
     * @returns the rounded value as a number
     */
    round = (val: number, precision?: number) =>
        getEditorResponseData<number>({
            data: String(round(val, precision)),
            success: true,
            status: 200,
            parsedData: null,
        });
 
    createEnvironmentBaseURL = (parameters: { type?: EnvironmentType; environment?: string; version?: string }) => {
        const { type = EnvironmentType.SANDBOX, environment = 'ft-nostress', version = '1' } = parameters;
        const host = type == EnvironmentType.SANDBOX ? 'chili-publish-sandbox' : 'chili-publish';
        return `https://${environment}.${host}.online/grafx/api/v${version}/environment/${environment}`;
    };
 
    /**
     * This method can help you stage a file to the CHILI GraFx Environment API for upload.
     * @param files The Files or Blobs to stage.
     * @param remoteConnectorId The connector ID from Environment API to stage the files for.
     * @param validationConfiguration The validation configuration to use for the files.
     * @returns Promise<FilePointer[]> referencing the staged data.
     */
    stageFiles = async (
        files: File[] | Blob[],
        remoteConnectorId: Id,
        validationConfiguration?: UploadValidationConfiguration,
    ): Promise<FilePointer[]> => {
        const envApiUrl = this.#localConfig.get(WellKnownConfigurationKeys.GraFxStudioEnvironmentApiUrl);
        if (!envApiUrl) {
            throw new Error('GraFx Studio Environment API URL is not set');
        }
 
        const stageUrl = `${envApiUrl}connectors/${remoteConnectorId}/stage`;
 
        const accessToken = this.#localConfig.get(WellKnownConfigurationKeys.GraFxStudioAuthToken);
        if (!accessToken) {
            throw new Error('GraFx Studio Auth Token is not set');
        }
 
        const formData = new FormData();
 
        // Add each file/blob to form data
        files.forEach((file, idx) => {
            const filename = file instanceof File ? file.name : `blob-${idx}`;
            formData.append('files', file, filename);
        });
 
        Eif (validationConfiguration) {
            formData.append(
                'validationJson',
                JSON.stringify({
                    allowedMimeTypes: validationConfiguration.mimeTypes,
                    minDimensions: {
                        width: validationConfiguration.minWidthPixels,
                        height: validationConfiguration.minHeightPixels,
                    },
                }),
            );
        }
 
        const response = await fetch(stageUrl, {
            method: 'POST',
            body: formData,
            headers: {
                Authorization: `Bearer ${accessToken}`,
            },
        });
 
        if (response.status === 422) {
            const data = await response.json();
            throw new UploadAssetValidationError(data.message, UploadAssetValidationErrorType.minDimension);
        }
 
        Iif (!response.ok) {
            throw new Error('Failed to stage files');
        }
 
        const data = await response.json();
        return data as FilePointer[];
    };
}