@tdanks2000/anilist-wrapper
Version:
A wrapper for the Anilist graphQL api
61 lines (60 loc) • 2.72 kB
JavaScript
;
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.API = void 0;
const exceptions_1 = require("./exceptions");
const BASE_URL = 'https://graphql.anilist.co';
class API {
constructor(access_token, options) {
this.access_token = access_token;
this.options = options;
}
get(query, variables) {
var _a;
return __awaiter(this, void 0, void 0, function* () {
if (!query)
throw new Error('No query provided');
if (query.startsWith('mutation') && this.access_token === null)
throw new exceptions_1.NotLoggedInException();
const controller = new AbortController();
const options = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
},
body: JSON.stringify({
query: query,
}),
};
if (variables)
options.body = JSON.stringify({ query, variables });
if (this.access_token)
options.headers.Authorization = `Bearer ${this.access_token}`;
try {
const res = yield fetch(BASE_URL, options);
const { status, statusText } = res;
if (status !== 200) {
if (statusText)
throw new Error(`Anilist Api returned with a ${status} status. ${statusText}`);
throw new Error(`Anilist Api returned with a ${status} status. The api might be down!`);
}
return (yield res.json());
}
catch (error) {
if (error.name === 'AbortError')
throw new exceptions_1.TimeOutException(((_a = this.options) === null || _a === void 0 ? void 0 : _a.timeout) || 5000);
throw new Error(error.message);
}
});
}
}
exports.API = API;