All files / src/utils EditorResponseData.ts

100% Statements 20/20
88.24% Branches 15/17
100% Functions 3/3
100% Lines 20/20

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      36x   36x 816x 816x 5x 5x             5x 2x 2x   2x   3x     811x 811x             5x 5x         36x 434x               36x       2x   2x      
import type { EditorResponse } from '../types/CommonTypes';
 
// This is an error code from the engine exception table, do not change
const connectorHttpErrorErrorCode = 404075;
 
export function getEditorResponseData<T>(response: EditorResponse<unknown>, parse = true): EditorResponse<T> {
    try {
        if (!response.success) {
            const parsedError = response.error ?? 'Yikes, something went wrong';
            const parsedCause = {
                cause: {
                    name: String(response.status),
                    message: response.error ?? 'Yikes, something went wrong',
                },
            };
 
            if (response.status === connectorHttpErrorErrorCode) {
                const parsedErrorData = JSON.parse(response.data as string);
                const httpStatusCode = parsedErrorData['statusCode'] as number;
 
                throw new ConnectorHttpError(httpStatusCode, parsedError, parsedCause);
            } else {
                throw new Error(parsedError, parsedCause);
            }
        }
        const dataShouldBeParsed = response.data && parse;
        return {
            ...response,
            parsedData: dataShouldBeParsed
                ? (JSON.parse(response.data as string) as T)
                : (response.data as unknown as T),
        };
    } catch (error) {
        console.error(error);
        throw error;
    }
}
 
// For testing purposes only
export function castToEditorResponse(toCast: unknown): EditorResponse<unknown> {
    return {
        status: 200,
        success: true,
        parsedData: null,
        data: JSON.stringify(toCast),
    };
}
 
export class ConnectorHttpError extends Error {
    statusCode: number;
 
    constructor(statusCode: number, message?: string, options?: ErrorOptions) {
        super(message, options);
 
        this.statusCode = statusCode;
    }
}