@nekolab/hanime
Version:
Fast and efficient hanime.tv API wrapper written in TypeScript.
56 lines (55 loc) • 1.93 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.RequestsClient = void 0;
const utility_1 = require("../modules/utility");
const errors_1 = require("../errors");
/**
* Requests client
*/
class RequestsClient {
/**
* Headers compiler function to use on each request
*/
headersCompiler;
/**
* Logging client
*/
loggingClient;
/**
* Create a new instance of the RequestsClient
* @param baseUrl Base URL for the requests
* @param headersCompiler Headers compiler function to use on each request
* @param loggingClient Logging client
* @returns RequestsClient instance
*/
constructor(headersCompiler, loggingClient) {
this.loggingClient = loggingClient;
this.headersCompiler = headersCompiler;
}
/**
* Make a request to the API
* @param path Path to request
* @param body Body to send
* @param method Method to use
* @returns Response from the API
*/
async request(baseUrl, path, body, method = 'GET') {
const headers = {
'Content-Type': 'application/json',
...this.headersCompiler({ baseUrl, path }),
};
this.loggingClient.debug(`${method} request to ${baseUrl}${path} (${JSON.stringify(headers)}): ${JSON.stringify(body)}`);
const rsp = await fetch(`${baseUrl}${path}`, {
method,
body: body && JSON.stringify((0, utility_1.convertToSnakeCase)(body)),
headers: headers,
});
const json = await rsp.json();
this.loggingClient.debug(`[${rsp.status}] Response of ${path} (${JSON.stringify(rsp.headers)}): ${JSON.stringify(json)}`);
if (!rsp.ok) {
throw new errors_1.APIError(json.errors?.[0] || null, rsp.status);
}
return (0, utility_1.convertToCamelCase)(json);
}
}
exports.RequestsClient = RequestsClient;