]> git.r.bdr.sh - rbdr/generador-de-insultos/blame - lib/Conjugator.js
Add CORS to raw endpoint
[rbdr/generador-de-insultos] / lib / Conjugator.js
CommitLineData
1a652aac
BB
1'use strict';
2
3
4var Promise = require('bluebird');
5var cheerio = require('cheerio');
6require('neon');
7var request = require('request');
8
9
10var Conjugator = Class({}, "Conjugator")({
11 prototype : {
12 _baseUrl: "http://www.spanishdict.com/conjugate/",
ecbfe403 13 _selector: ".vtable-word",
1a652aac
BB
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);
ecbfe403 31 result = $(this._selector)[10];
1a652aac
BB
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
66module.exports = Conjugator;