From 7dce7e704ff3215405aff68a7c3e1aa6af0d6415 Mon Sep 17 00:00:00 2001 From: Kelly Bielaski Date: Tue, 19 Sep 2023 10:16:01 -0700 Subject: [PATCH] Add logging --- src/services/webhooks.ts | 60 +++++++++++++++++++++++----------------- 1 file changed, 34 insertions(+), 26 deletions(-) diff --git a/src/services/webhooks.ts b/src/services/webhooks.ts index 1c7eb9d..7228fa3 100644 --- a/src/services/webhooks.ts +++ b/src/services/webhooks.ts @@ -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 => { - 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 => {