-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathgenerate.js
86 lines (68 loc) · 1.93 KB
/
generate.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
const fs = require("fs");
const path = require("path");
const axios = require("axios").default;
const dotenv = require('dotenv');
// Get local .env
dotenv.config();
const { GITHUB_TOKEN } = process.env;
const baseUrl = "https://api.github.com/users";
let arr = [];
// Randomize list
function randomizeList(array) {
let currentIndex = array.length,
randomIndex;
while (currentIndex != 0) {
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex--;
[array[currentIndex], array[randomIndex]] = [
array[randomIndex],
array[currentIndex],
];
}
return array;
}
// Get github profile by username
async function getUserV2(username, data) {
try {
const response = await axios.get(`${baseUrl}/${username}`, {
headers: {
Accept: "application/vnd.github+json",
Authorization: `Bearer ${GITHUB_TOKEN}`
}
});
const resData = response?.data || { avatar: "", name: "" };
data.forEach((item) => {
const payload = {
id: +new Date(),
jokes: item.jokes,
avatar: `${resData?.avatar_url}&s=100` || "",
name: resData?.name || resData?.login,
username,
};
arr.push(payload);
});
arr = randomizeList(arr);
fs.writeFileSync(
"./src/assets/jokes.json",
JSON.stringify({ data: arr }, null, 4)
);
console.info('Success get user of ', username);
} catch (error) {
const errorResult = error?.response?.data ?? error;
const result = {
username,
error: errorResult?.message,
};
console.table(result);
}
}
// Get json file
const jsonsInDir = fs
.readdirSync("./src/data")
.filter((file) => path.extname(file) === ".json");
// Read each of item from src/data
jsonsInDir.forEach((file) => {
const fileData = fs.readFileSync(path.join("./src/data", file));
const jsonParsed = JSON.parse(fileData.toString());
getUserV2(jsonParsed.author, jsonParsed.data);
});