import ErrorResponse from '../exceptions/ErrorResponse';

export class HttpResponse<responseObject, requestBody = unknown> {
    public url: string;
    public response: responseObject;
    public code: number;
    public requestBody: requestBody | undefined

    constructor(response: responseObject, code: number, url: string, requestBody?: requestBody) {
        this.url = url;
        this.response = response;
        this.code = code;
        this.requestBody = requestBody;
    }

    public isErrorResponseCode() {
        return this.code >= 400;
    }

    public handleErrorResponse() {
        if (this.isErrorResponseCode()) {
            throw new ErrorResponse(
                `error connecting with external service, status code: ${
                    this.code
                }, response: ${JSON.stringify(this.response)}`
            );
        }
    }

    public handleEmptyResponse() {
        if (
            this.response === null ||
            this.response === undefined ||
            this.response === ''
        ) {
            throw new ErrorResponse('empty response');
        }
    }
}
