Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Get random hadith of a language doesnt exist here is a function in node please add it or a equivalent #69

Open
hossam1231 opened this issue Sep 29, 2023 · 0 comments

Comments

@hossam1231
Copy link

const fetch = require('node-fetch');

async function getRandomHadith(editions) {
// Select a random book
const randomBook = editions[Math.floor(Math.random() * editions.length)];

// Generate a random Hadith number (assuming the book has at least 1035 Hadiths)
var randomHadithNo = Math.floor(Math.random() * 11035) + 1;

// Construct the URL for the random Hadith
const url = https://cdn.jsdelivr.net/gh/fawazahmed0/hadith-api@1/editions/${randomBook.collection[0].name}/${randomHadithNo}.json;

try {
const response = await fetch(url);
if (response.status === 200) {
const hadith = await response.json();
// console.log(Random Hadith from ${randomBook.bookName}:);
// console.log(hadith);
return hadith
} else {
console.log(url)
console.error(Error fetching Hadith: ${response.statusText});
randomHadithNo = Math.floor(Math.random() * 1035) + 1;
return getRandomHadith(editions)
}
} catch (error) {
console.error(Error: ${error.message});
}
}

function sortByLanguage(data, desiredLanguage) {
const editions = [];

for (const key in data) {
const edition = data[key];
if (edition.collection.some(item => item.language === desiredLanguage)) {
// Check if the edition has the desired language in its collection
const language = edition.language;

  // Push the edition object into the 'editions[language]' array
  editions.push({
    name: edition.name,
    collection: edition.collection.filter(item => item.language === desiredLanguage),
  });
}

}

return getRandomHadith(editions)
}

async function listEditions() {
try {
const url = 'https://cdn.jsdelivr.net/gh/fawazahmed0/hadith-api@1/editions.json';

// Use the fetch function to make the GET request
const response = await fetch(url);

// Check if the response status is OK (200)
if (!response.ok) {
  throw new Error(`HTTP error! Status: ${response.status}`);
}

// Parse the JSON response
const data = await response.json();

// Call sortByLanguage with the desired language (e.g., 'English')
return sortByLanguage(data, 'English');
} catch (error) {
console.error('Error fetching data:', error.message);
return null;
}
}

export async function main_getHadith() {
// Usage example
return await listEditions();
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant