Skip to content

Instantly share code, notes, and snippets.

@plasmadice
Last active June 11, 2023 04:11
Show Gist options
  • Save plasmadice/bfffcbbcb479b3010d3d64903dffc2dd to your computer and use it in GitHub Desktop.
Save plasmadice/bfffcbbcb479b3010d3d64903dffc2dd to your computer and use it in GitHub Desktop.
getRecentCommitCount - Get a user's GitHub commit count within a timeframe using fetch()
export async function getRecentCommitCount(username: string, email: string, days: number = 30) {
let totalCommits = 0
let page = 1
const perPage = 100
const timeFrame = new Date()
timeFrame.setDate(timeFrame.getDate() - days)
let stop = false
// Loop through pages until we find a commit outside of our timeframe
while (!stop) {
// Fetch last 100 events from GitHub API for User
// retrieves private events if you are authenticated and fetching your own events
const response = await fetch(
`https://api.github.com/users/${username}/events?page=${page}&per_page=${perPage}`,
{
headers : {
Accept: "application/vnd.github.v3+json",
Authorization: process.env.GITHUB_TOKEN ? `Bearer ${process.env.GITHUB_TOKEN}` : '',
}
}
)
const data = await response.json()
if (data.length) {
// filter out non-commit events and events older than {days} days and events that are not by {email}
const recentCommitEvents = data.filter((event) => {
return (
event.type === "PushEvent" &&
new Date(event.created_at) >= timeFrame &&
event.payload?.commits?.some((commit) => commit.author?.email.includes(email))
)
})
// count commits in each event authored by {email}
totalCommits += recentCommitEvents?.reduce((acc, event) => {
const userCommits = event.payload?.commits?.filter(
(commit) => commit.author?.email.includes(email)
)
return (acc += userCommits?.length)
}, 0)
// check if the last event is older than {days} days, if true, stop the loop
if (new Date(data[data.length - 1].created_at) < timeFrame) {
stop = true
}
} else {
stop = true
}
page++
}
return totalCommits
}
// Retrieve last 30 days
const commitsInLastMonth = getRecentCommitCount("plasmadice", process.env.GITHUB_EMAIL as string)
// Retrieve last 7 days
const commitsInLastMonth = getRecentCommitCount("plasmadice", process.env.GITHUB_EMAIL as string, 7)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment