-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathindex.js
105 lines (88 loc) · 2.64 KB
/
index.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
require('dotenv').config()
const axios = require('axios')
const { Octokit } = require("@octokit/rest");
const wrapAnsi = require("wrap-ansi");
const baseURL = 'https://dev.to/api/articles'
const {
GIST_ID: gistId,
GH_TOKEN: githubToken,
DEV_USERNAME: devUsername
} = process.env;
const options = {
params: {
username: devUsername
}
}
const octokit = new Octokit({
auth: `token ${githubToken}`
});
function truncate(str, n){
return (str.length > n) ? str.substr(0, n-2) + '…' : str;
};
async function getPost() {
try {
const response = await axios.get(baseURL, options);
const post = response.data[0];
await updateGist(post)
} catch (error) {
console.error(error);
}
}
async function createComment() {
let gist_comment;
try {
await octokit.gists.createComment({
gist_id: gistId,
body: 'The post link goes here'
});
gist_comment = await octokit.gists.listComments({ gist_id: gistId });
} catch (error) {
console.error(`Unable to create comment\n${error}`);
}
return gist_comment;
}
async function updateGist(post) {
let gist;
let gist_comment;
try {
gist = await octokit.gists.get({ gist_id: gistId });
gist_comment = await octokit.gists.listComments({ gist_id: gistId });
} catch (error) {
console.error(`Unable to get gist\n${error}`);
}
if(gist_comment.data.length == 0)
gist_comment = await createComment()
const filename = Object.keys(gist.data.files)[0];
const commentId = gist_comment.data[0].id;
const tags = '#' + post.tag_list.join(", #");
const content = `📜 ${truncate(post.title, 54).replace(/\s+/g, ' ')} \n ▶ ${
truncate(post.description, 100).replace(/\s+/g, ' ')
} \n🔖 ${tags} \n📆 ${post.readable_publish_date.replace(/\s+/g, ' ')} | 🔗 Link in comments`;
try {
await octokit.gists.update({
gist_id: gistId,
description: `dev.to/${devUsername} | ❤ ${post.public_reactions_count} | 💬 ${
post.comments_count
}`,
files: {
[filename]: {
content: wrapAnsi(content, 60, { hard: true, trim: false })
}
}
});
} catch (error) {
console.error(`Unable to update gist\n${error}`);
}
try {
await octokit.gists.updateComment({
gist_id: gistId,
comment_id: commentId,
body: `[Link to post](${post.url})`
});
} catch (error) {
console.error(`Unable to update gist comment\n${error}`);
}
}
(async () => {
await getPost();
})();