forked from xdevplatform/Twitter-API-v2-sample-code
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbookmarks-lookup-js-sdk.js
92 lines (79 loc) · 2.49 KB
/
bookmarks-lookup-js-sdk.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
const { Client, auth } = require("twitter-api-sdk");
const readline = require("readline").createInterface({
input: process.stdin,
output: process.stdout,
});
//Helper function to parse callback
const getQueryStringParams = (query) => {
return query
? (/^[?#]/.test(query) ? query.slice(1) : query)
.split(/[\?\&]/)
.reduce((params, param) => {
let [key, value] = param.split("=");
params[key] = value
? decodeURIComponent(value.replace(/\+/g, " "))
: "";
return params;
}, {})
: {};
};
//Helper terminal input function
async function input(prompt) {
return new Promise(async (resolve, reject) => {
readline.question(prompt, (out) => {
readline.close();
resolve(out);
});
});
}
// The code below sets the consumer key and consumer secret from your environment variables
// To set environment variables on macOS or Linux, run the export commands below from the terminal:
// export CLIENT_ID='YOUR-CLIENT-ID'
// export CLIENET_SECRET='YOUR-CLIENT-SECRET'
const CLIENT_ID = process.env.CLIENT_ID;
const CLIENT_SECRET = process.env.CLIENT_SECRET;
// Optional parameters for additional payload data
const params = {
expansions: "author_id",
"user.fields": ["username", "created_at"],
"tweet.fields": ["geo", "entities", "context_annotations"],
};
(async () => {
const authClient = new auth.OAuth2User({
client_id: CLIENT_ID,
client_secret: CLIENT_SECRET,
callback: "https://www.example.com/oauth",
scopes: ["tweet.read", "users.read", "bookmark.read"],
});
const client = new Client(authClient);
const STATE = "my-state";
//Get authorization
const authUrl = authClient.generateAuthURL({
state: STATE,
code_challenge: "challenge",
});
console.log(`Please go here and authorize:`, authUrl);
//Input users callback url in termnial
const redirectCallback = await input("Paste the redirected callback here: ");
try {
//Parse callback
const { state, code } = getQueryStringParams(redirectCallback);
if (state !== STATE) {
console.log("State isn't matching");
}
//Gets access token
await authClient.requestAccessToken(code);
//Get the user ID
const {
data: { id },
} = await client.users.findMyUser();
//Makes api call
const getBookmark = await client.bookmarks.getUsersIdBookmarks(id, params);
console.dir(getBookmark, {
depth: null,
});
process.exit();
} catch (error) {
console.log(error);
}
})();