Created
September 29, 2024 16:16
-
-
Save ali-master/b41051e937381a41fd7b3793d193b87a to your computer and use it in GitHub Desktop.
NodeJS Hook0
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import axios from "axios"; | |
import { randomUUID } from 'crypto'; | |
const checkProcessEnv = () => { | |
if ( | |
!process.env.HOOK0_APPLICATION_ID || | |
!process.env.HOOK0_APPLICATION_SECRET | |
) { | |
throw new Error('Cannot subscribe to webhooks without Hook0 settings'); | |
} | |
} | |
const ingest = async (event: string, payload: object) => { | |
checkProcessEnv(); | |
await axios.post( | |
'https://app.hook0.com/api/v1/event/', | |
{ | |
application_id: process.env.HOOK0_APPLICATION_ID, | |
event_type: event, | |
event_id: randomUUID(), | |
labels: { | |
all: 'yes', | |
}, | |
occurred_at: new Date().toISOString(), | |
payload_content_type: 'application/json', | |
payload: JSON.stringify(payload), | |
}, | |
{ | |
headers: { | |
Authorization: `Bearer ${process.env.HOOK0_APPLICATION_SECRET}`, | |
Accept: 'application/json', | |
'Content-Type': 'application/json', | |
}, | |
}, | |
); | |
}; | |
const subscribe = async ( | |
eventType: string, | |
webhookUrl: string, | |
subscriptionDescription: string, | |
) => { | |
checkProcessEnv(); | |
// TODO check if the eventType already exists or not. If not, throw a clear error message because hook0 API throws a 500 otherwise. See https://gitlab.com/hook0/hook0/-/issues/53 | |
// TODO check if subscription already exists | |
const result = await axios.post( | |
'https://app.hook0.com/api/v1/subscriptions/', | |
{ | |
application_id: process.env.HOOK0_APPLICATION_ID, | |
description: subscriptionDescription, | |
is_enabled: true, | |
event_types: [eventType], | |
label_key: 'all', | |
label_value: 'yes', | |
metadata: {}, | |
target: { | |
type: 'http', | |
method: 'POST', | |
url: webhookUrl, | |
headers: {}, | |
}, | |
}, | |
{ | |
headers: { | |
Authorization: `Bearer ${process.env.HOOK0_APPLICATION_SECRET}`, | |
Accept: 'application/json', | |
'Content-Type': 'application/json', | |
}, | |
}, | |
); | |
return { | |
secret: result.data.secret, | |
subscription_id: result.data.subscription_id, | |
}; | |
} | |
export default { | |
ingest, | |
subscribe, | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment