-
Notifications
You must be signed in to change notification settings - Fork 0
/
fetch.js
93 lines (85 loc) · 2.06 KB
/
fetch.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
const fs = require("fs");
const https = require("https");
const process = require("process");
require("dotenv").config();
const GITHUB_TOKEN = process.env.REACT_APP_GITHUB_TOKEN;
const GITHUB_USERNAME = process.env.GITHUB_USERNAME;
const USE_GITHUB_DATA = process.env.USE_GITHUB_DATA;
const ERR = {
noUserName:
"Github Username was found to be undefined. Please set all relevant environment variables.",
requestFailed:
"The request to GitHub didn't succeed. Check if GitHub token in your .env file is correct."
};
if (USE_GITHUB_DATA === "true") {
if (GITHUB_USERNAME === undefined) {
throw new Error(ERR.noUserName);
}
console.log(`Fetching profile data for ${GITHUB_USERNAME}`);
var data = JSON.stringify({
query: `
{
user(login:"${GITHUB_USERNAME}") {
name
bio
isHireable
avatarUrl
location
pinnedItems(first: 6, types: [REPOSITORY]) {
totalCount
edges {
node {
... on Repository {
name
description
forkCount
stargazers {
totalCount
}
url
id
diskUsage
primaryLanguage {
name
color
}
}
}
}
}
}
}
`
});
const default_options = {
hostname: "api.github.com",
path: "/graphql",
port: 443,
method: "POST",
headers: {
Authorization: `Bearer ${GITHUB_TOKEN}`,
"User-Agent": "Node"
}
};
const req = https.request(default_options, res => {
let data = "";
console.log(`statusCode: ${res.statusCode}`);
if (res.statusCode !== 200) {
throw new Error(ERR.requestFailed);
}
res.on("data", d => {
data += d;
});
res.on("end", () => {
fs.writeFile("./public/profile.json", data, function (err) {
if (err) return console.log(err);
console.log("saved file to public/profile.json");
});
});
});
req.on("error", error => {
throw error;
});
req.write(data);
req.end();
}