mirror of
https://gitlab.com/openstapps/openstapps.git
synced 2026-01-18 07:32:54 +00:00
72 lines
1.8 KiB
TypeScript
72 lines
1.8 KiB
TypeScript
/*
|
|
* Copyright (C) 2018 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 * as request from 'request';
|
|
|
|
/**
|
|
* Request options that requires a url
|
|
*/
|
|
export interface RequestOptions extends request.CoreOptions {
|
|
url: URL;
|
|
}
|
|
|
|
/**
|
|
* Response with generic for the type of body that is returned from the request
|
|
*/
|
|
export interface Response<TYPE_OF_BODY> extends request.Response {
|
|
body: TYPE_OF_BODY;
|
|
}
|
|
|
|
/**
|
|
* HTTP client that is based on request
|
|
*/
|
|
export class HttpClient {
|
|
/**
|
|
* Make a request
|
|
* @param requestConfig Configuration of the request
|
|
*/
|
|
request<TYPE_OF_BODY>(
|
|
requestConfig: RequestOptions,
|
|
): Promise<Response<TYPE_OF_BODY>> {
|
|
const params: request.CoreOptions = {
|
|
body: {},
|
|
followAllRedirects: true,
|
|
json: true,
|
|
method: 'GET',
|
|
};
|
|
|
|
if (typeof requestConfig.body !== 'undefined') {
|
|
params.body = requestConfig.body;
|
|
}
|
|
|
|
if (typeof requestConfig.headers !== 'undefined') {
|
|
params.headers = requestConfig.headers;
|
|
}
|
|
|
|
if (requestConfig.method !== 'GET') {
|
|
params.method = requestConfig.method;
|
|
}
|
|
|
|
return new Promise((resolve, reject) => {
|
|
request(requestConfig.url.toString(), params, (err, response) => {
|
|
if (err) {
|
|
return reject(err);
|
|
}
|
|
|
|
resolve(response);
|
|
});
|
|
});
|
|
}
|
|
}
|