UNPKG

mute-english-api

Version:

提供英语词典和百度翻译等API服务的npm包,支持多种翻译服务集成

123 lines (107 loc) 3.53 kB
/** * 英语词典API服务模块 * 提供英语单词查询功能 */ import configManager from '../config/index.js'; /** * 获取单词的词典信息 * @param {string} word - 要查询的英语单词 * @returns {Promise<Array>} - 词典数据数组 */ export async function fetchTranslation(word) { try { if (!word || typeof word !== 'string') { throw new Error('单词参数不能为空且必须是字符串'); } const config = configManager.getDictionaryApiConfig(); const response = await fetch(`${config.apiUrl}/${word}`); if (!response.ok) { throw new Error(`HTTP错误: ${response.status}`); } return await response.json(); } catch (error) { console.error("获取词典信息失败:", error); throw error; } } /** * 获取单词的基本释义 * @param {string} word - 要查询的英语单词 * @returns {Promise<Object>} - 包含成功状态和释义的对象 */ export async function getWordMeaning(word) { try { const data = await fetchTranslation(word); if (!data || !Array.isArray(data) || data.length === 0) { return { success: false, error: '未找到该单词的释义', word: word, meanings: [] }; } const meanings = []; // 提取释义信息 data.forEach(entry => { if (entry.meanings && Array.isArray(entry.meanings)) { entry.meanings.forEach(meaning => { meanings.push({ partOfSpeech: meaning.partOfSpeech || '未知词性', definitions: meaning.definitions?.map(def => ({ definition: def.definition, example: def.example || null, synonyms: def.synonyms || [], antonyms: def.antonyms || [] })) || [] }); }); } }); return { success: true, word: word, phonetics: data[0]?.phonetics || [], meanings: meanings, sourceUrls: data[0]?.sourceUrls || [] }; } catch (error) { return { success: false, error: error.message, word: word, meanings: [] }; } } /** * 获取单词的发音信息 * @param {string} word - 要查询的英语单词 * @returns {Promise<Object>} - 包含发音信息的对象 */ export async function getWordPhonetics(word) { try { const data = await fetchTranslation(word); if (!data || !Array.isArray(data) || data.length === 0) { return { success: false, error: '未找到该单词的发音信息', word: word, phonetics: [] }; } return { success: true, word: word, phonetics: data[0]?.phonetics || [] }; } catch (error) { return { success: false, error: error.message, word: word, phonetics: [] }; } } // 导出默认对象以保持兼容性 export default fetchTranslation;