]> git.r.bdr.sh - rbdr/generador-de-insultos/blob - lib/Conjugator.js
d45e1fe9eb85626cff8ce383a8a8e40b9ae61dc8
[rbdr/generador-de-insultos] / lib / Conjugator.js
1 'use strict';
2
3
4 var Promise = require('bluebird');
5 var cheerio = require('cheerio');
6 require('neon');
7 var request = require('request');
8
9
10 var Conjugator = Class({}, "Conjugator")({
11 prototype : {
12 _baseUrl: "http://www.spanishdict.com/conjugate/",
13 _selector: ".vtable-word",
14
15 init : function init(config) {
16 config = config || {};
17
18 Object.keys(config).forEach(function (property) {
19 this[property] = config[property];
20 }, this);
21 },
22
23 conjugate : function conjugate(verb) {
24 return new Promise(function (resolve, reject) {
25 request(this._baseUrl + verb, function (err, res, body) {
26 var $, result, finalVerb ;
27 if (err) {
28 return reject(err);
29 }
30 $ = cheerio.load(body);
31 result = $(this._selector)[10];
32
33 if (!result) {
34 console.log("Verb not found: ", verb);
35 return reject(new Error("Not a valid verb"));
36 }
37
38 finalVerb = this._extractWord(result);
39
40 console.log(verb, finalVerb);
41 resolve(finalVerb);
42 }.bind(this));
43 }.bind(this));
44 },
45
46 _extractWord : function _extractWord(node) {
47 var word = "", components;
48
49 node.children.forEach(function (child) {
50 if (child.type === "text") {
51 word += child.data;
52 } else {
53 word += this._extractWord(child);
54 }
55 }, this);
56
57 word = word.split(",")[0]; // multiple conjugations, take 1
58 components = word.split(" "); // some special cases have two words
59 // use the last, why not
60
61 return components[components.length - 1];
62 }
63 }
64 });
65
66 module.exports = Conjugator;