anime-quotes-sdk
Version:
A Node.js SDK to fetch a random quote from a pre-fetched list of quotes.
70 lines (61 loc) • 2.33 kB
JavaScript
const axios = require('axios');
class AnimeSDK {
constructor() {
this.apiUrl = "https://raw.githubusercontent.com/wolfgunblood/anime-quotes/main/data.json";
this.allQuotes = [];
this.isFetching = false;
}
async fetchQuotes() {
if (this.isFetching) {
return new Promise((resolve, reject) => {
const checkFetch = setInterval(() => {
if (!this.isFetching) {
clearInterval(checkFetch);
this.allQuotes.length > 0 ? resolve(this.allQuotes) : reject(new Error('Failed to fetch quotes.'));
}
}, 100);
});
}
this.isFetching = true;
try {
const response = await axios.get(this.apiUrl);
this.allQuotes = response.data;
} catch (error) {
console.error('Error fetching quotes:', error);
this.allQuotes = [];
throw error;
} finally {
this.isFetching = false;
}
return this.allQuotes;
}
async getRandomQuote() {
if (this.allQuotes.length === 0) {
await this.fetchQuotes();
}
let quote;
do {
const randomIndex = Math.floor(Math.random() * this.allQuotes.length);
quote = this.allQuotes[randomIndex];
} while (quote.Character && quote.Character.length >= 400);
const { Index, ...quoteWithoutIndex } = quote;
return quoteWithoutIndex;
}
async getRandomQuoteByAnime(animeName) {
if (this.allQuotes.length === 0) {
await this.fetchQuotes();
}
let filteredQuotes = this.allQuotes.filter(quote => quote.Anime && quote.Anime.toLowerCase() === animeName.toLowerCase());
if (filteredQuotes.length === 0) {
return null;
}
let quote;
do {
const randomIndex = Math.floor(Math.random() * filteredQuotes.length);
quote = filteredQuotes[randomIndex];
} while (quote.Character && quote.Character.length >= 400);
const { Index, ...quoteWithoutIndex } = quote;
return quoteWithoutIndex;
}
}
module.exports = AnimeSDK;