-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
70 lines (64 loc) · 1.87 KB
/
server.js
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
59
60
61
62
63
64
65
66
67
68
69
70
const express = require("express");
const Twitter = require("twit");
const AYLIENTextAPI = require("aylien_textapi");
const app = express();
const client = new Twitter({
consumer_key: "TWITTER_CONSUMER_KEY",
consumer_secret: "TWITTER_CONSUMER_SECRET",
access_token: "TWITTER_ACCESS_TOKEN",
access_token_secret: "TWITTER_ACCESS_TOKEN_SECRET"
});
const textapi = new AYLIENTextAPI({
application_id: "AYLIEN_APPLICATION_ID",
application_key: "AYLIEN_APPLICATION_KEY"
});
const nbrOfTweetsInSearch = 10;
app.use(require("cors")());
app.use(require("body-parser").json());
const sentiment = (text, callback) => {
textapi.sentiment(text, (err, resp) => {
if (err !== null) {
console.log(`Error: ${err}`);
} else {
callback(text, resp.polarity);
}
});
};
app.get("/api/search/:text", (req, res) => {
client
.get("search/tweets", {
q: req.params.text
})
.then(data => {
const tweets = data.data.statuses;
const jsonData = { tweets: [] };
let i = 0;
let SCRIPT = `sentimentTable: LOAD * Inline [text, sentiment\n`;
tweets.forEach(item => {
if (i < nbrOfTweetsInSearch) {
i += 1;
sentiment(item.text, (tweet, results) => {
SCRIPT += `${escape(tweet)},${results}\n`;
const itemData = {};
itemData.text = tweet;
itemData.sentiment = results;
jsonData.tweets.push(itemData);
if (jsonData.tweets.length === nbrOfTweetsInSearch) {
SCRIPT += "];";
res.send({ script: SCRIPT });
}
});
}
});
});
});
app.get("api/sentiment/:text", (req, res) => {
textapi.sentiment(req.params.text, (err, resp) => {
if (err !== null) {
console.log(`Error: ${err}`);
} else {
res.send(resp);
}
});
});
app.listen(3000, () => console.log("Server running"));