-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathgetTweets.js
120 lines (93 loc) · 2.86 KB
/
getTweets.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
const credentials = require('./credentials');
var https = require('https');
const { threadId } = require('worker_threads');
const apiKey = process.env.API_KEY || credentials.API_KEY;
const apiKeySecret = process.env.API_KEY_SECRET || credentials.API_KEY_SECRET;
const bearerToken = process.env.BEARER_TOKEN || credentials.BEARER_TOKEN;
//Creates the URL object from the hostname
//We will work with this object to hit the various endpoints of the API
const requestUrl = new URL('https://api.twitter.com');
//path to see specific tweets by id
const tweetsPath = "/2/tweets";
//path to search for recent tweets
const searchRecentPath = "/1.1/search/tweets.json";
requestUrl.pathname = searchRecentPath;
const options = {
headers: {
'authorization': `Bearer ${bearerToken}`
}
}
function searchByUser(user_name) {
return new Promise((resolve, reject) => {
let params = new URLSearchParams([
['from',`${user_name}`]
]);
const options = {
headers: {
'authorization': `Bearer ${bearerToken}`
}
}
requestUrl.search = params;
const req = https.request(requestUrl,options, (res) => {
if (res.statusCode < 200 || res.statusCode >= 300) {
return reject(new Error('statusCode=' + res.statusCode));
}
var str = " "
var tweets;
res.on('data', function(chunk) {
str += chunk
});
res.on('end', function() {
try {
tweets = JSON.parse(str)
} catch(e) {
reject(e);
}
resolve(tweets);
});
});
req.on('error', (e) => {
reject(e.message);
});
req.end();
});
}
function searchByHashtag(hashtag) {
return new Promise((resolve, reject) => {
let params = new URLSearchParams([
['q',`%23${hashtag}`]
]);
const options = {
headers: {
'authorization': `Bearer ${bearerToken}`
}
}
requestUrl.search = params;
const req = https.request(requestUrl,options, (res) => {
if (res.statusCode < 200 || res.statusCode >= 300) {
return reject(new Error('statusCode=' + res.statusCode));
}
var str = " "
var tweets;
res.on('data', function(chunk) {
str += chunk
});
res.on('end', function() {
try {
tweets = JSON.parse(str)
} catch(e) {
reject(e);
}
resolve(tweets);
});
});
req.on('error', (e) => {
reject(e.message);
});
req.end();
});
}
module.exports = {
searchByUser : searchByUser,
searchByHashtag : searchByHashtag
}