-
Notifications
You must be signed in to change notification settings - Fork 76
Expand file tree
/
Copy pathgithubApi.js
More file actions
71 lines (59 loc) · 1.84 KB
/
githubApi.js
File metadata and controls
71 lines (59 loc) · 1.84 KB
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
const axios = require('axios');
const redisClient = require('../util/RediaClient');
const User = require('../models/UserModel');
const { createGithubApi } = require('../util/GithubApiHelper');
const githubApi = axios.create({
baseURL: 'https://api.github.com',
headers: {
'Accept': 'application/vnd.github.v3+json',
},
});
// Utility to robustly strip .git from repo names
function stripGitSuffix(name) {
if (typeof name === 'string' && name.toLowerCase().endsWith('.git')) {
return name.slice(0, -4);
}
return name;
}
exports.fetchReadme = async (req, res) => {
const { username } = req.params;
let { reponame } = req.params;
reponame = stripGitSuffix(reponame);
try {
const githubApi = await createGithubApi(req.session);
const response = await githubApi.get(
`/repos/${username}/${reponame}/readme`
);
res.json(response.data);
} catch (error) {
const status = error.response?.status || 500;
res
.status(status)
.json({ message: 'Error fetching README from GitHub.' });
}
};
exports.fetchRepoDetails = async (req, res) => {
const { username } = req.params;
let { reponame } = req.params;
if (reponame.endsWith('.git')) {
reponame = reponame.slice(0, -4);
}
const cacheKey = `repo:${username}:${reponame}`;
try {
const cachedData = await redisClient.get(cacheKey);
if (cachedData) return res.json(JSON.parse(cachedData));
const githubApi = await createGithubApi(req.session);
const response = await githubApi.get(
`/repos/${username}/${reponame}`
);
await redisClient.set(cacheKey, JSON.stringify(response.data), {
EX: 3600,
});
res.json(response.data);
} catch (error) {
const status = error.response?.status || 500;
res
.status(status)
.json({ message: 'Error fetching repository data from GitHub.' });
}
};