]> git.r.bdr.sh - rbdr/generador-de-insultos/blob - lib/Conjugator.js
c4e74f7e6c6ca4094865ea8a83a319a19d39b3f5
[rbdr/generador-de-insultos] / lib / Conjugator.js
1 'use strict';
2
3 const Cheerio = require('cheerio');
4 const Fetch = require('node-fetch');
5
6 const internals = {
7 kBaseUrl: 'http://www.spanishdict.com/conjugate/',
8 kSelector: 'table .ex-tip',
9 kThirdPersonPresentPosition: 10,
10
11 extractWord(node) {
12
13 let word = '';
14
15 node.children.forEach(function (child) {
16
17 if (child.type === 'text') {
18 word += child.data;
19 } else {
20 word += internals.extractWord(child);
21 }
22 });
23
24 word = word.split(',')[0]; // multiple conjugations, take 1
25
26 const components = word.split(' '); // some special cases have two words
27 // use the last, why not
28
29 return components[components.length - 1];
30 }
31 };
32
33 module.exports = {
34 async conjugate(verb) {
35
36 console.debug(`Conjugating ${verb}`);
37
38 const response = await Fetch(internals.kBaseUrl + verb);
39 const body = await response.text();
40
41 const $ = Cheerio.load(body);
42 const result = $(internals.kSelector)[internals.kThirdPersonPresentPosition];
43
44 if (!result) {
45 console.error('Verb not found: ', verb);
46 throw new Error('Not a valid verb');
47 }
48
49 const plainTextVerb = internals.extractWord(result);
50 console.debug(verb, plainTextVerb);
51
52 return plainTextVerb;
53 }
54 };