pointercrate
Version:
Unofficial Pointercrate API wrapper written in TypeScript
58 lines (57 loc) • 2.03 kB
JavaScript
const fetch = require("node-fetch");
/**
* The base of the Pointercrate class. Used to send requests to the Pointercrate API.
*/
class BasePointercrate {
/**
* @param api An optional url string specifing what API to send requests to.
*/
constructor(api = "https://pointercrate.com/api") {
this.api = api;
}
/**
* A function to send requests to the Pointercrate API.
* @param path The path to the endpoint of the request.
* @param options Options to send into the request, if specified.
* @returns A response, containing a `body`, and `headers`.
*/
async sendRequest(path, options = { method: "GET", headers: {}, body: {} }) {
options.method = options.method ? options.method.toUpperCase() : "GET";
options.headers = options.headers || {};
options.body = options.body || {};
let url = this.api + path;
let init;
if (options.method == "GET" || options.method == "HEAD") {
if (!Object.is(options.body, {}))
url += "/?" + new URLSearchParams(options.body).toString();
init = {
headers: options.headers
};
}
else {
init.method = options.method;
init.headers = {
...init.headers,
"Content-Type": "application/json"
};
init.body = options.body;
}
let response = await fetch.default(url, init);
let body;
if ((await response.text()).length > 0)
body = await response.json();
else
body = {};
let headers = {};
if (body.hasOwnProperty("message"))
throw new Error(body.message);
for (let header of response.headers.keys()) {
headers[header] = response.headers.get(header);
}
return {
body,
headers
};
}
}
module.exports = BasePointercrate;