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 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 19x 19x 19x 19x 19x 18x 2x 16x 16x 16x 1x 15x 15x 9x 6x 1x 2x 1x 9x 2x 2x 2x 2x 2x | import fetch, { RequestInit } from "node-fetch";
import AbortController from "abort-controller";
import querystring from "query-string";
import { ErrorWithCode, ExtendedError } from "./error";
/**
* Ошибка, которую выбрасывает Http API при неправильном коде ответа
*/
export class HttpError extends ErrorWithCode<number> {
/**
*
* @param {number} code Код ответа
* @param {number} body Тело ответа
*/
constructor(public code: number, public body: string) {
super(`API Responded with Error response code: ${code}`, code);
}
/**
*
* @return {Error}
*/
toJSON(): Error & { code: number; body: string } {
return {
message: this.message,
name: this.name,
stack: this.stack,
code: this.code,
body: this.body
};
}
}
export type Agent = RequestInit["agent"];
/**
* Ошибка раскодировки ответа сервера
*/
export class DecodingError extends ExtendedError {}
/**
*
*/
export class HttpAPI {
protected readonly API_URL: string = "";
protected readonly API_HEADERS: Record<string, string> = {};
protected readonly API_TIMEOUT: number = 10_000;
protected readonly API_OK_RESPONSE_CODES: number[] = [200];
protected agent?: Agent;
/**
* Simplified http request function
*
* @throws {HttpError} If http error code is not matched valid
* @throws {DecodingError} If unable to decode response
*
* @param {string} url Relative to API url path
* @param {string} method Http request method
* @param {Record<string, string>} headers Additional headers to API
* @param {string?} body Request body
*
* @return {Promise<*>} Decoded response
*/
protected async _request(
url: string,
method: string,
headers: Record<string, string>,
body?: string | undefined
): Promise<any> {
const absoluteUrl =
url.startsWith("https://") || url.startsWith("http://")
? url
: `${this.API_URL}///${url}`.replace(/\/{3,}/g, "/");
// ^^^ 3 cлеша не встречаются в URL, поэтому их можно
// использовать как костыль для нормализации. Чтобы было не GET //path, а GET /path
const abortController = new AbortController();
const timeout = setTimeout(() => abortController.abort(), this.API_TIMEOUT);
const response = await fetch(absoluteUrl, {
method,
headers: { ...this.API_HEADERS, ...headers },
body,
agent: this.agent,
signal: abortController.signal
}).finally(() => clearTimeout(timeout));
if (method.toLowerCase() === "head") {
return undefined;
}
const contentType = response.headers.get("content-type")?.split(";")[0];
const responseBuffer = await response.buffer();
if (!this.API_OK_RESPONSE_CODES.includes(response.status)) {
throw new HttpError(response.status, responseBuffer.toString());
}
try {
if (contentType?.startsWith("text/")) return responseBuffer.toString();
switch (contentType) {
case "application/json":
return JSON.parse(responseBuffer.toString());
case "application/x-www-form-urlencoded":
return querystring.parse(responseBuffer.toString());
}
return responseBuffer;
} catch (error: any) {
throw new DecodingError(error.message);
}
}
/**
* Делает GET запрос и парсит ответ
* @template T
* @param {string} url URL запроса
* @param {Record<string, string>=} headers Заголовки запроса
* @return {Promise<T>}
*/
protected async get<T = any>(
url: string,
headers: Record<string, string> = {}
): Promise<T> {
return await this._request(url, "GET", headers);
}
/**
* Делает HEAD запрос и парсит ответ
* @template T
* @param {string} url URL запроса
* @param {Record<string, string>=} headers Заголовки запроса
* @return {Promise<T>}
*/
protected async head<T>(
url: string,
headers: Record<string, string> = {}
): Promise<T> {
return await this._request(url, "HEAD", headers);
}
/**
* Делает POST запрос и парсит ответ
* @template T
*
* @param {string} url URL запроса
* @param {Record<string, string>=} headers Заголовки запроса
* @param {string=} body Тело запроса
*
* @return {Promise<T>}
*/
protected async post<T>(
url: string,
headers: Record<string, string> = {},
body?: string | undefined
): Promise<T> {
return await this._request(url, "POST", headers, body);
}
/**
* Делает PUT запрос и парсит ответ
* @template T
*
* @param {string} url URL запроса
* @param {Record<string, string>=} headers Заголовки запроса
* @param {string=} body Тело запроса
*
* @return {Promise<T>}
*/
protected async put<T>(
url: string,
headers: Record<string, string> = {},
body?: string | undefined
): Promise<T> {
return await this._request(url, "PUT", headers, body);
}
/**
* Делает PATCH запрос и парсит ответ
* @template T
*
* @param {string} url URL запроса
* @param {Record<string, string>=} headers Заголовки запроса
* @param {string=} body Тело запроса
*
* @return {Promise<T>}
*/
protected async patch<T>(
url: string,
headers: Record<string, string> = {},
body?: string | undefined
): Promise<T> {
return await this._request(url, "PATCH", headers, body);
}
/**
* Делает DELETE запрос и парсит ответ
* @template T
*
* @param {string} url URL запроса
* @param {Record<string, string>=} headers Заголовки запроса
* @param {string=} body Тело запроса
*
* @return {Promise<T>}
*/
protected async delete<T>(
url: string,
headers: Record<string, string> = {},
body?: string | undefined
): Promise<T> {
return await this._request(url, "DELETE", headers, body);
}
}
|