Skip to content

Commit

Permalink
Merge pull request #63 from atlassian-labs/no-issue/add-logging
Browse files Browse the repository at this point in the history
Add logging
  • Loading branch information
kbielaski authored Sep 19, 2023
2 parents 8f3a7ac + 7dce7e7 commit 8a1dba3
Showing 1 changed file with 34 additions and 26 deletions.
60 changes: 34 additions & 26 deletions src/services/webhooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,33 +5,41 @@ import { GITLAB_EVENT_WEBTRIGGER, STORAGE_KEYS, STORAGE_SECRETS } from '../const
import { generateSignature } from '../utils/generate-signature-utils';

export const setupAndValidateWebhook = async (groupId: number): Promise<number> => {
const [existingWebhook, groupToken] = await Promise.all([
storage.get(`${STORAGE_KEYS.WEBHOOK_KEY_PREFIX}${groupId}`),
storage.getSecret(`${STORAGE_SECRETS.GROUP_TOKEN_KEY_PREFIX}${groupId}`),
]);

const isWebhookValid = existingWebhook && (await getGroupWebhook(groupId, existingWebhook, groupToken)) !== null;

if (isWebhookValid) {
return existingWebhook;
console.log('Setting up webhook');
try {
const [existingWebhook, groupToken] = await Promise.all([
storage.get(`${STORAGE_KEYS.WEBHOOK_KEY_PREFIX}${groupId}`),
storage.getSecret(`${STORAGE_SECRETS.GROUP_TOKEN_KEY_PREFIX}${groupId}`),
]);

const isWebhookValid = existingWebhook && (await getGroupWebhook(groupId, existingWebhook, groupToken)) !== null;

if (isWebhookValid) {
console.log('Using existing webhook');
return existingWebhook;
}

const webtriggerURL = await webTrigger.getUrl(GITLAB_EVENT_WEBTRIGGER);
const webtriggerURLWithGroupId = `${webtriggerURL}?groupId=${groupId}`;
const webhookSignature = generateSignature();
const webhookId = await registerGroupWebhook({
groupId,
url: webtriggerURLWithGroupId,
token: groupToken,
signature: webhookSignature,
});

await Promise.all([
storage.set(`${STORAGE_KEYS.WEBHOOK_KEY_PREFIX}${groupId}`, webhookId),
storage.set(`${STORAGE_KEYS.WEBHOOK_SIGNATURE_PREFIX}${groupId}`, webhookSignature),
]);

console.log('Successfully created webhook');
return webhookId;
} catch (e) {
console.log('Error setting up webhook, ', e);
return null;
}

const webtriggerURL = await webTrigger.getUrl(GITLAB_EVENT_WEBTRIGGER);
const webtriggerURLWithGroupId = `${webtriggerURL}?groupId=${groupId}`;
const webhookSignature = generateSignature();
const webhookId = await registerGroupWebhook({
groupId,
url: webtriggerURLWithGroupId,
token: groupToken,
signature: webhookSignature,
});

await Promise.all([
storage.set(`${STORAGE_KEYS.WEBHOOK_KEY_PREFIX}${groupId}`, webhookId),
storage.set(`${STORAGE_KEYS.WEBHOOK_SIGNATURE_PREFIX}${groupId}`, webhookSignature),
]);

return webhookId;
};

export const deleteWebhook = async (groupId: number): Promise<void> => {
Expand Down

0 comments on commit 8a1dba3

Please sign in to comment.