UNPKG

cambridge-dictionary-api

Version:

API for Cambridge Dictionary

70 lines (69 loc) 2.72 kB
"use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __exportStar = (this && this.__exportStar) || function(m, exports) { for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); }; Object.defineProperty(exports, "__esModule", { value: true }); exports.DictionaryError = void 0; exports.fetchDictionaryWord = fetchDictionaryWord; const axios_1 = require("axios"); const cheerio = require("cheerio"); const helpers_1 = require("./helpers"); const DICTIONARY_URL = `${helpers_1.BASE_URL}/us/dictionary/english/`; const USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"; const MAX_RETRIES = 3; const RETRY_DELAY_MS = 2000; class DictionaryError extends Error { constructor(message) { super(message); this.name = "DictionaryError"; } } exports.DictionaryError = DictionaryError; async function fetchDictionaryWord(entry, retries = MAX_RETRIES) { try { const html = await fetchHtml(DICTIONARY_URL + entry); const $ = cheerio.load(html); return { word: $(".hw.dhw").first().text().trim(), dialects: (0, helpers_1.extractDialects)($), definitions: (0, helpers_1.extractDefinitions)($), derivedForms: (0, helpers_1.extractDerivedForms)($), }; } catch (error) { return handleRetry(error, entry, retries); } } async function fetchHtml(url) { try { const { data } = await axios_1.default.get(url, { headers: { "User-Agent": USER_AGENT }, timeout: 3000, }); return data; } catch (error) { throw new Error(`Failed to fetch HTML: ${error.message}`); } } async function handleRetry(error, entry, retries) { if (retries > 0) { console.warn(`Error: ${error.message}. Retrying (${retries} left)...`); await new Promise((res) => setTimeout(res, RETRY_DELAY_MS * (MAX_RETRIES - retries + 1))); return fetchDictionaryWord(entry, retries - 1); } return new DictionaryError(error.message || "Failed to fetch dictionary data"); } __exportStar(require("./interfaces"), exports); __exportStar(require("./enums"), exports);