router_function_githook.js
const crypto = require('crypto');
const simpleGit = require('simple-git');
const { exec } = require('child_process');
const { KeiLog } = require('../../lib/Logger');
const GITHUB_WEBHOOK_SECRET = 'kei';
const PM2_PROCESS_NAME = 'WA_TENDEAN';
/**
* Module for handling GitHub Webhooks to automate code deployment and restart a PM2 process.
*@module githook
* @param {object} app - The Express application object.
*/
module.exports = async function (app) {
app.post('/githook', (req, res) => {
// Verify GitHub secret
const signature = req.get('X-Hub-Signature-256');
const hmac = crypto.createHmac('sha256', GITHUB_WEBHOOK_SECRET);
const digest = 'sha256=' + hmac.update(req.rawBody).digest('hex');
if (!signature || !crypto.timingSafeEqual(Buffer.from(digest), Buffer.from(signature))) {
return res.status(400).send('Invalid signature');
}
// If event is a push event, stash local changes, pull the latest code with rebase, apply stashed changes, and restart PM2 process
if (req.get('X-GitHub-Event') === 'push') {
const git = simpleGit();
KeiLog('INFO',"MENERIMA PUSH DARI GITHUB .. ");
git.stash().add('.').commit('Auto-committing before pull').pull('origin', 'main', {'--rebase': 'true'}, (err, update) => {
if(err) {
console.error(`Error during git operations: ${err}`);
return res.status(500).send('Internal server error');
}
git.stash(['apply'], (stashErr, result) => {
if(stashErr) {
console.error(`Error applying stash: ${stashErr}`);
}
if(update) {
KeiLog('INFO',"RESTARTING .. ");
exec(`pm2 restart ${PM2_PROCESS_NAME}`, (err, stdout, stderr) => {
if (err) {
console.error(`Error restarting PM2 process: ${stderr}`);
return res.status(500).send('Internal server error');
}
console.log(`PM2 process restarted: ${stdout}`);
res.sendStatus(200);
});
} else {
res.sendStatus(200);
}
});
});
} else {
res.sendStatus(200);
}
});
};