Skip to content

Commit 2518f1c

Browse files
feat: added new issues and new pr fetch logic (#1)
* feat: refactored new issue logic * feat: refactored new pr logic
1 parent cde0a9b commit 2518f1c

File tree

2 files changed

+117
-97
lines changed

2 files changed

+117
-97
lines changed

action/monitor-new-issue.js

Lines changed: 60 additions & 54 deletions
Original file line numberDiff line numberDiff line change
@@ -26,59 +26,66 @@ const slackWrapper = (token, channel) => {
2626

2727
const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
2828

29-
const fetchIssuesWithinTimeFrame = async (gitToken, owner, repo, daysAgo, hoursAgo) => {
30-
const apiUrl = `https://api.github.com/repos/${owner}/${repo}/issues?state=open`;
31-
const now = new Date();
32-
const sinceDate = new Date(now.getTime() - daysAgo * 24 * 60 * 60 * 1000);
33-
const cutoffDate = new Date(now.getTime() - hoursAgo * 60 * 60 * 1000);
34-
35-
let issuesWithinTimeFrame = [];
36-
let page = 1;
37-
let olderIssueFound = false;
38-
39-
try {
40-
while (true) {
41-
const response = await axios.get(apiUrl, {
42-
headers: { Authorization: `token ${gitToken}` },
43-
params: {
44-
page,
45-
per_page: 100,
46-
since: sinceDate.toISOString(),
47-
},
48-
});
49-
50-
const issues = response.data.filter((issue) => !issue.pull_request);
51-
52-
const recentIssues = issues.filter((issue) => {
53-
const createdAt = new Date(issue.created_at);
54-
if (createdAt < cutoffDate) {
55-
olderIssueFound = true;
56-
return false;
57-
}
58-
return createdAt <= now;
59-
});
60-
61-
issuesWithinTimeFrame.push(
62-
...recentIssues.map((issue) => ({
63-
title: issue.title,
64-
url: issue.html_url,
65-
createdAt: issue.created_at,
66-
labels: issue.labels.map((label) => label.name),
67-
comments: issue.comments,
68-
}))
69-
);
70-
71-
if (olderIssueFound || !response.headers["link"]?.includes('rel="next"')) break;
72-
73-
page++;
29+
/**
30+
* Fetch new issues created within a configurable timeframe.
31+
*
32+
* @param {string} gitToken - GitHub API token for authentication.
33+
* @param {string} owner - Repository owner.
34+
* @param {string} repo - Repository name.
35+
* @param {number} hoursAgo - Timeframe in hours to fetch issues created since then.
36+
* @returns {Promise<Array>} - List of new issues created within the specified timeframe.
37+
*/
38+
const fetchNewIssues = async (gitToken, owner, repo, hoursAgo) => {
39+
const apiUrl = `https://api.github.com/repos/${owner}/${repo}/issues`;
40+
const sinceDate = new Date(new Date().getTime() - hoursAgo * 60 * 60 * 1000).toISOString();
41+
42+
let newIssues = [];
43+
let page = 1;
44+
45+
try {
46+
while (true) {
47+
const response = await axios.get(apiUrl, {
48+
headers: { Authorization: `token ${gitToken}` },
49+
params: {
50+
state: "open", // Only fetch open issues
51+
sort: "created", // Sort by creation date
52+
direction: "desc", // Fetch the most recent issues first
53+
since: sinceDate, // Fetch issues created or updated after this timestamp
54+
per_page: 100, // Maximum results per page
55+
page, // Current page of the results
56+
},
57+
});
58+
59+
const issues = response.data.filter((issue) => {
60+
// Exclude pull requests and ensure the issue is newly created
61+
const createdAt = new Date(issue.created_at);
62+
return !issue.pull_request && createdAt >= new Date(sinceDate);
63+
});
64+
65+
// Map issues to include required fields
66+
newIssues.push(
67+
...issues.map((issue) => ({
68+
title: issue.title,
69+
url: issue.html_url,
70+
createdAt: issue.created_at,
71+
labels: issue.labels.map((label) => label.name),
72+
comments: issue.comments,
73+
}))
74+
);
75+
76+
// Exit loop if no more pages to fetch
77+
if (!response.headers["link"]?.includes('rel="next"')) break;
78+
79+
page++; // Move to the next page
80+
}
81+
82+
return newIssues;
83+
} catch (error) {
84+
console.error("Error fetching issues:", error.message);
85+
return [];
7486
}
87+
};
7588

76-
return issuesWithinTimeFrame;
77-
} catch (error) {
78-
console.error("Error fetching issues:", error.message);
79-
return [];
80-
}
81-
};
8289

8390
const sendSlackNotification = async (slackToken, slackChannel, slackIDType, slackID, issues, repo) => {
8491
if (!issues.length) {
@@ -119,10 +126,9 @@ const sendSlackNotification = async (slackToken, slackChannel, slackIDType, slac
119126
};
120127

121128
async function monitorIssues(gitToken, slackToken, slackChannel, owner, repo, slackIDType, slackID) {
122-
const fetchDaysAgo = 1;
123-
const filterHoursAgo = 6;
129+
const hoursAgo = 6;
124130

125-
const issues = await fetchIssuesWithinTimeFrame(gitToken, owner, repo, fetchDaysAgo, filterHoursAgo);
131+
const issues = await fetchNewIssues(gitToken, owner, repo, hoursAgo);
126132
console.log("Issues to be notified via Slack:", issues.map((issue) => issue.title));
127133

128134
await sendSlackNotification(slackToken, slackChannel, slackIDType, slackID, issues, repo);

action/monitor-new-pr.js

Lines changed: 57 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -31,51 +31,65 @@ const slackWrapper = (token, channel) => {
3131
};
3232
};
3333

34+
/**
35+
* Fetch new pull requests created within the last `daysAgo` days.
36+
*
37+
* @param {string} gitToken - GitHub API token for authentication.
38+
* @param {string} owner - Repository owner.
39+
* @param {string} repo - Repository name.
40+
* @param {number} daysAgo - Timeframe in days to fetch PRs created since then. Default: 1 day.
41+
* @returns {Promise<Array>} - List of new pull requests created within the specified timeframe.
42+
*/
3443
const fetchNewPRs = async (gitToken, owner, repo, daysAgo = 1) => {
35-
const apiUrl = `https://api.github.com/repos/${owner}/${repo}/pulls?state=open`;
36-
const cutoffDate = new Date(
37-
new Date().getTime() - daysAgo * 24 * 60 * 60 * 1000
38-
);
39-
40-
let newPRs = [];
41-
let page = 1;
42-
43-
console.log(`Fetching PRs from ${apiUrl}`);
44-
45-
try {
46-
while (true) {
47-
console.log(`Fetching page ${page}...`);
48-
const response = await axios.get(apiUrl, {
49-
headers: { Authorization: `token ${gitToken}` },
50-
params: { page, per_page: 100 },
51-
});
52-
53-
const recentPRs = response.data.filter((pr) => {
54-
const createdAt = new Date(pr.created_at);
55-
return pr.user?.login !== "dependabot[bot]" && createdAt >= cutoffDate;
56-
});
57-
58-
newPRs.push(
59-
...recentPRs.map((pr) => ({
60-
author: pr.user.login,
61-
title: pr.title,
62-
url: pr.html_url,
63-
createdAt: pr.created_at,
64-
labels: pr.labels.map((label) => label.name),
65-
}))
66-
);
67-
68-
const linkHeader = response.headers["link"];
69-
if (!linkHeader || !linkHeader.includes('rel="next"')) break;
70-
71-
page++;
44+
const apiUrl = `https://api.github.com/repos/${owner}/${repo}/pulls`;
45+
const cutoffDate = new Date(Date.now() - daysAgo * 24 * 60 * 60 * 1000).toISOString();
46+
47+
let newPRs = [];
48+
let page = 1;
49+
50+
console.log(`Fetching new PRs created in the last ${daysAgo} days from ${apiUrl}`);
51+
52+
try {
53+
while (true) {
54+
console.log(`Fetching page ${page}...`);
55+
const response = await axios.get(apiUrl, {
56+
headers: { Authorization: `token ${gitToken}` },
57+
params: {
58+
state: "open", // Fetch only open PRs
59+
per_page: 100, // Maximum results per page
60+
page, // Current page of the results
61+
},
62+
});
63+
64+
const recentPRs = response.data.filter((pr) => {
65+
const createdAt = new Date(pr.created_at);
66+
// Exclude PRs created by dependabot and older than the cutoff date
67+
return pr.user?.login !== "dependabot[bot]" && createdAt >= new Date(cutoffDate);
68+
});
69+
70+
newPRs.push(
71+
...recentPRs.map((pr) => ({
72+
author: pr.user.login,
73+
title: pr.title,
74+
url: pr.html_url,
75+
createdAt: pr.created_at,
76+
labels: pr.labels.map((label) => label.name),
77+
}))
78+
);
79+
80+
const hasNextPage = response.headers["link"]?.includes('rel="next"');
81+
if (!hasNextPage) break;
82+
83+
page++;
84+
}
85+
86+
console.log(`Fetched ${newPRs.length} new PR(s)`);
87+
return newPRs;
88+
} catch (error) {
89+
console.error("Error fetching PRs:", error.message);
90+
return [];
7291
}
73-
return newPRs;
74-
} catch (error) {
75-
console.error("Error fetching PRs from GitHub:", error.message);
76-
return [];
77-
}
78-
};
92+
};
7993

8094
const sendSlackNotification = async (prs, slackToken, slackChannel, slackIDType, slackID, repo) => {
8195
if (prs.length === 0) {

0 commit comments

Comments
 (0)