Here’s a Node.js implementation for a GitHub webhook listener that automates child team approval when a new team is added to a hierarchy:
- Install Node.js.
- Use
express
to create the server andaxios
for HTTP requests. - Install required packages:
npm install express body-parser axios
const express = require('express');
const bodyParser = require('body-parser');
const axios = require('axios');
const app = express();
const PORT = 5000;
const GITHUB_TOKEN = "your_github_token";
const GITHUB_API_URL = "https://api.github.com/graphql";
app.use(bodyParser.json());
// Webhook endpoint
app.post('/webhook', async (req, res) => {
const payload = req.body;
if (payload.action === 'created') {
const teamSlug = payload.team.slug;
const organization = payload.organization.login;
const parentTeamSlug = payload.team.parent?.slug;
if (parentTeamSlug) {
try {
await approveChildTeam(organization, teamSlug, parentTeamSlug);
console.log(`Successfully approved child team: ${teamSlug}`);
} catch (error) {
console.error(`Failed to approve child team: ${teamSlug}`, error.response?.data || error.message);
}
}
}
res.status(200).send('Webhook received and processed.');
});
// Function to approve child team relationship
async function approveChildTeam(organization, childTeamSlug, parentTeamSlug) {
const mutation = `
mutation AddTeamToParent($organization: String!, $parentSlug: String!, $childSlug: String!) {
updateTeamParent(input: {
organization: $organization,
parentTeamSlug: $parentSlug,
teamSlug: $childSlug
}) {
team {
id
name
parentTeam {
id
name
}
}
}
}`;
const variables = {
organization,
parentSlug: parentTeamSlug,
childSlug: childTeamSlug,
};
const headers = {
Authorization: `Bearer ${GITHUB_TOKEN}`,
'Content-Type': 'application/json',
};
const response = await axios.post(
GITHUB_API_URL,
{ query: mutation, variables },
{ headers }
);
return response.data;
}
// Start the server
app.listen(PORT, () => {
console.log(`Webhook listener is running on port ${PORT}`);
});
-
Set Up Webhook in GitHub:
- Go to your Organization Settings > Webhooks.
- Add a new webhook with the URL
http://your-server-ip-or-domain:5000/webhook
. - Choose
application/json
as the content type. - Select the
team
event.
-
Run the Script: Start the Node.js server:
node index.js
-
Add a New Team: When a new team is created and set as a child of another team, the webhook will automatically attempt to approve the relationship.
- Ensure the GitHub token has
admin:org
permissions. - Deploy this script to a production-grade server if it needs to handle live events.
- Add logging or error-handling mechanisms for better debugging and monitoring.
- If deploying to a public server, set up proper security measures (e.g., validating the webhook secret).