mirror of
https://gitlab.com/openstapps/openstapps.git
synced 2026-01-11 04:03:34 +00:00
46 lines
1.6 KiB
TypeScript
46 lines
1.6 KiB
TypeScript
/*
|
|
* 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 <https://www.gnu.org/licenses/>.
|
|
*/
|
|
import type {HttpClientInterface, HttpClientRequest, HttpClientResponse} from './http-client-interface.js';
|
|
import type {SCResponses} from '@openstapps/core';
|
|
|
|
/**
|
|
* HTTP client that is based on request
|
|
*/
|
|
export class HttpClient implements HttpClientInterface {
|
|
/**
|
|
* Make a request
|
|
* @param requestConfig Configuration of the request
|
|
*/
|
|
async request<T extends SCResponses>(requestConfig: HttpClientRequest): Promise<HttpClientResponse<T>> {
|
|
const parameters: RequestInit = {
|
|
method: requestConfig.method ?? 'GET',
|
|
headers: requestConfig.headers ?? {},
|
|
};
|
|
|
|
if (requestConfig.body !== undefined) {
|
|
(parameters.headers as Record<string, string>)['Content-Type'] = 'application/json';
|
|
parameters.body = JSON.stringify(requestConfig.body);
|
|
}
|
|
|
|
const response = await fetch(requestConfig.url, parameters);
|
|
|
|
return {
|
|
body: await response.json().catch(() => response.text().catch(() => undefined)),
|
|
headers: response.headers,
|
|
statusCode: response.status,
|
|
};
|
|
}
|
|
}
|