/* * Copyright (C) 2019-2022 Open StApps * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see . */ import got, {OptionsOfJSONResponseBody, Response as GotResponse} from 'got'; /** * Request options that requires a url * Note: adjust request options of got library for backward compatibility */ export interface RequestOptions extends Omit { /** * Body of the request */ // TODO: Use a specific type? // eslint-disable-next-line @typescript-eslint/no-explicit-any body?: any; /** * Target URL of the request */ url: URL; } /** * Response with generic for the type of body that is returned from the request */ export interface Response extends GotResponse { /** * Typed body of the response */ body: TYPE_OF_BODY; } /** * HTTP client that is based on request */ export class HttpClient { /** * Make a request * * @param requestConfig Configuration of the request */ async request(requestConfig: RequestOptions): Promise> { const parameters: OptionsOfJSONResponseBody = { followRedirect: true, method: 'GET', responseType: 'json', }; if (typeof requestConfig.body !== 'undefined') { parameters.json = requestConfig.body; } if (typeof requestConfig.headers !== 'undefined') { parameters.headers = requestConfig.headers; } if (typeof requestConfig.method !== 'undefined') { parameters.method = requestConfig.method; } let response: Response; try { response = await got(requestConfig.url.toString(), parameters); } catch (error) { // eslint-disable-next-line @typescript-eslint/no-explicit-any if (typeof (error as any).response === 'undefined') { throw error; } // if there is a response (e.g. response with statusCode 404 etc.) provide it // eslint-disable-next-line @typescript-eslint/no-explicit-any response = (error as any).response as Response; } return response; } }