66 lines
2.1 KiB
JavaScript
66 lines
2.1 KiB
JavaScript
const { formatMessage } = require('./formatters')
|
|
|
|
/**
|
|
* Normalize GitHub webhook payload to common format
|
|
* @param {Object} payload - GitHub webhook payload
|
|
* @returns {Object} - Normalized webhook data
|
|
*/
|
|
const normalizeGithubPayload = (payload) => {
|
|
// Validate required fields
|
|
if (!payload?.repository?.full_name || !payload?.repository?.html_url || !payload?.ref) {
|
|
return {
|
|
repository: {
|
|
full_name: payload?.repository?.full_name || 'unknown',
|
|
html_url: payload?.repository?.html_url || '#',
|
|
id: payload?.repository?.id || 0
|
|
},
|
|
ref: payload?.ref || 'unknown',
|
|
commits: []
|
|
}
|
|
}
|
|
|
|
// Handle missing or invalid commits array
|
|
const commits = Array.isArray(payload.commits) ? payload.commits : []
|
|
|
|
return {
|
|
repository: {
|
|
full_name: payload.repository.full_name,
|
|
html_url: payload.repository.html_url,
|
|
id: payload.repository.id || 0
|
|
},
|
|
ref: payload.ref,
|
|
commits: commits.map(commit => ({
|
|
id: commit.id || `${Date.now()}-${Math.random()}`,
|
|
message: commit.message || 'No message',
|
|
stats: {
|
|
additions: Number(commit.stats?.additions) || 0,
|
|
deletions: Number(commit.stats?.deletions) || 0
|
|
}
|
|
}))
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Handle GitHub webhook
|
|
* @param {Object} payload - Webhook payload
|
|
* @param {Set} reportedCommits - Set of reported commit hashes
|
|
* @param {Map} commitTimestamps - Map of commit timestamps
|
|
* @returns {string|null} - Formatted message or null if no new commits
|
|
*/
|
|
const handleGithub = (payload, reportedCommits, commitTimestamps) => {
|
|
const data = normalizeGithubPayload(payload)
|
|
|
|
// Filter new commits
|
|
const newCommits = data.commits.filter(commit => {
|
|
if (reportedCommits.has(commit.id)) return false
|
|
reportedCommits.add(commit.id)
|
|
commitTimestamps.set(commit.id, Date.now())
|
|
return true
|
|
})
|
|
|
|
if (newCommits.length === 0) return null
|
|
|
|
return formatMessage(data, newCommits)
|
|
}
|
|
|
|
module.exports = { handleGithub }
|