pipebomb.js
Version:
Library for interacting with Pipe Bomb servers
62 lines • 2.11 kB
JavaScript
import Axios from "axios";
import Response from "./Response.js";
export default class Request {
constructor(method, url, jwt, body) {
this.responseHandlers = [];
let request;
if (["get", "delete"].includes(method)) {
request = Axios[method](url, {
headers: {
Authorization: jwt ? "JWT " + jwt : undefined
}
});
}
else {
request = Axios[method](url, body, {
headers: {
Authorization: jwt ? "JWT " + jwt : undefined
}
});
}
request.then(success => {
if (success.status == 204) {
const response = new Response(204, "No Content", null);
for (let callback of this.responseHandlers) {
callback(response);
}
return;
}
this.sendResponse(success.data);
}, error => {
if (error?.response?.data?.statusCode)
return this.sendResponse(error.response.data);
const response = new Response(error.errno, error.code, error.cause);
for (let callback of this.responseHandlers) {
callback(response);
}
});
}
addSuccessHandler(callback) {
this.responseHandlers.push(callback);
return this;
}
sendResponse(data) {
let response;
try {
if (typeof data?.statusCode != "number")
throw "Malformed response";
if (typeof data?.statusMessage != "string")
throw "Malformed response";
if (!("response" in data))
throw "Malformed response";
response = new Response(data.statusCode, data.statusMessage, data.response);
}
catch (e) {
response = new Response(500, "Internal Server Error", data);
}
for (let callback of this.responseHandlers) {
callback(response);
}
}
}
//# sourceMappingURL=Request.js.map