UNPKG

@irfanshadikrishad/anilist

Version:

Minimalist unofficial AniList CLI for Anime and Manga Enthusiasts

61 lines (60 loc) 2.79 kB
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()); }); }; import fetch from 'node-fetch'; import { Auth } from './auth.js'; import { aniListEndpoint, handleRateLimitRetry } from './workers.js'; /** * Sends a GraphQL request to the AniList API. * * This function constructs a request with the provided query and variables, * handles authorization, and processes the API response. If a rate-limit error (429) is returned, * it waits for 1 minute and retries the request. * * @param {string} query - The AniList GraphQL query to be executed. * @param {object} variables - An object containing the variables for the query. * @returns {Promise<object|null>} The response from the API as a JSON object if successful; otherwise, null. */ function fetcher(query, variables) { return __awaiter(this, void 0, void 0, function* () { var _a, _b; try { const headers = { 'content-type': 'application/json', }; const token = (yield Auth.isLoggedIn()) ? yield Auth.RetriveAccessToken() : null; if (token) headers['Authorization'] = `Bearer ${token}`; const request = yield fetch(aniListEndpoint, { method: 'POST', headers: headers, body: JSON.stringify({ query, variables }), }); const response = yield request.json(); if (request.status === 200) { return response; } else if (request.status === 429) { yield handleRateLimitRetry(60); return yield fetcher(query, variables); } else { console.error(`\n${request.status} ${((_b = (_a = response === null || response === void 0 ? void 0 : response.errors) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.message) || 'Unknown error'}.`); return null; } } catch (error) { console.error(`\nSomething went wrong. ${error.message}.`); return null; } }); } export { fetcher };