local.js•1.43 kB
import { readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
const jokes = loadJokes();
export async function getJoke(preferences) {
const { category, lang } = preferences;
const candidates = filterCandidates(category, lang);
if (candidates.length === 0) {
throw new Error('No local jokes available for the given filters');
}
const chosen = pickRandom(candidates);
return {
text: chosen.text,
category: chosen.category,
source: 'local-fallback',
};
}
function filterCandidates(category, lang) {
const normalizedCategory = category ? String(category).trim().toLowerCase() : undefined;
const normalizedLang = lang ? String(lang).trim().toLowerCase() : undefined;
const primary = jokes.filter((joke) =>
(!normalizedCategory || joke.category === normalizedCategory) &&
(!normalizedLang || joke.lang === normalizedLang)
);
if (primary.length > 0) {
return primary;
}
if (normalizedLang) {
const sameLang = jokes.filter((joke) => joke.lang === normalizedLang);
if (sameLang.length > 0) {
return sameLang;
}
}
return jokes;
}
function pickRandom(items) {
const index = Math.floor(Math.random() * items.length);
return items[index];
}
function loadJokes() {
const filePath = fileURLToPath(new URL('../../local-jokes.json', import.meta.url));
const file = readFileSync(filePath, 'utf8');
return JSON.parse(file);
}