masto
Version:
Mastodon API client for JavaScript, TypeScript, Node.js, browsers
86 lines (85 loc) • 3.42 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.HttpNativeImpl = void 0;
const index_js_1 = require("../errors/index.js");
const base_http_js_1 = require("./base-http.js");
const get_encoding_js_1 = require("./get-encoding.js");
class HttpNativeImpl extends base_http_js_1.BaseHttp {
serializer;
config;
logger;
constructor(serializer, config, logger) {
super();
this.serializer = serializer;
this.config = config;
this.logger = logger;
}
async request(params) {
const request = this.createRequest(params);
try {
this.logger?.log("info", `↑ ${request.method} ${request.url}`);
this.logger?.log("debug", "\tbody", {
encoding: params.encoding,
body: params.body,
});
const response = await fetch(request);
if (!response.ok) {
throw response;
}
const text = await response.text();
const encoding = (0, get_encoding_js_1.getEncoding)(response.headers);
if (!encoding) {
throw new index_js_1.MastoUnexpectedError("The server returned data with an unknown encoding.");
}
const data = this.serializer.deserialize(encoding, text);
this.logger?.log("info", `↓ ${request.method} ${request.url}`);
this.logger?.log("debug", "\tbody", text);
return {
headers: response.headers,
data: data,
};
}
catch (error) {
this.logger?.log("debug", `HTTP failed`, error);
throw await this.createError(error);
}
}
createRequest(params) {
const { method, path, search, encoding = "json", requestInit = {}, } = params;
const url = this.config.resolvePath(path, search);
const body = this.serializer.serialize(encoding, params.body);
const init = this.config.mergeRequestInitWithDefaults(requestInit);
const request = new Request(url, {
method,
body,
...init,
});
if (typeof body === "string" && encoding === "json") {
request.headers.set("Content-Type", "application/json");
}
return request;
}
async createError(error) {
if (error instanceof Response) {
const encoding = (0, get_encoding_js_1.getEncoding)(error.headers);
if (!encoding) {
throw new index_js_1.MastoUnexpectedError("The server returned data with an unknown encoding. The server may be down.");
}
const data = this.serializer.deserialize(encoding, await error.text());
const { error: message, errorDescription, details, ...additionalProperties } = data;
return new index_js_1.MastoHttpError({
statusCode: error.status,
message: message,
description: errorDescription,
details: details,
additionalProperties,
}, { cause: error });
}
if (error instanceof DOMException && error.name === "TimeoutError") {
return new index_js_1.MastoTimeoutError(`Request timed out`, { cause: error });
}
/* c8 ignore next */
return error;
}
}
exports.HttpNativeImpl = HttpNativeImpl;