all files / lib/ yandex.js

94.74% Statements 18/19
50% Branches 1/2
100% Functions 10/10
94.44% Lines 17/18
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58                              11×                                                    
import got from 'got';
 
function Yandex(translateKey, dictionaryKey) {
	this.translateKey = translateKey;
	this.dictionaryKey = dictionaryKey;
};
 
const get = (url, query) => got(url, { json: true, query }).then(_ => _.body);
 
// https://tech.yandex.ru/translate/doc/dg/reference/translate-docpage/
Yandex.prototype.translate = function(fromLang, toLang, text) {
	return get('https://translate.yandex.net/api/v1.5/tr.json/translate', {
		key: this.translateKey,
		lang: `${fromLang}-${toLang}`,
		text
	})
	.then(_ => _.text.join(' '));
};
 
// https://tech.yandex.ru/dictionary/doc/dg/reference/lookup-docpage/
Yandex.prototype.dictionary = function(fromLang, toLang, text) {
	return get('https://dictionary.yandex.net/api/v1/dicservice.json/lookup', {
		key: this.dictionaryKey,
		lang: `${fromLang}-${toLang}`,
		ui: 'en',
		flags: 4, // MORPHO = 0x0004 - включает поиск по форме слова;
		text
	})
	.then(_ => _.def);
};
 
Yandex.prototype.spellCheck = function(lang, text) {
	return get('https://speller.yandex.net/services/spellservice.json/checkText', {
		options: 256,
		lang,
		text
	})
	.then(corrections => {
		Eif (corrections.length > 0) {
			let prev = 0;
			let result = '';
 
			corrections.forEach(correction => {
				result += text.slice(prev, correction.pos);
				result += correction.s;
 
				prev = correction.pos + correction.len;
			});
 
			return result;
		} else {
			return text;
		}
	});
};
 
export default Yandex;