|
| 1 | +import { logger } from './util'; |
| 2 | +import { discordConfig, appConfig } from './config'; |
| 3 | + |
| 4 | +interface Embed { |
| 5 | + title: string; |
| 6 | + description: string; |
| 7 | +} |
| 8 | + |
| 9 | +interface DiscordMessage { |
| 10 | + username: string; |
| 11 | + content: string; |
| 12 | + embeds?: Embed[]; |
| 13 | +} |
| 14 | + |
| 15 | +interface Notifier { |
| 16 | + discord(msg: string, object?: any): Promise<void>; |
| 17 | + email(to: string, subject: string, body: string): Promise<void>; |
| 18 | +} |
| 19 | + |
| 20 | +interface NotifyParams { |
| 21 | + discordUrl?: string; |
| 22 | + environment?: string; |
| 23 | + botUsername?: string; |
| 24 | + httpClient?: (url: string, options: RequestInit) => Promise<Response>; |
| 25 | +} |
| 26 | + |
| 27 | +export function notify(params: NotifyParams = {}): Notifier { |
| 28 | + const { |
| 29 | + discordUrl = discordConfig.url, |
| 30 | + environment = appConfig.NODE_ENV, |
| 31 | + botUsername = 'commit.jaw.dev', |
| 32 | + httpClient = fetch, |
| 33 | + } = params; |
| 34 | + |
| 35 | + return { |
| 36 | + discord: async (msg: string, object: any = null): Promise<void> => { |
| 37 | + try { |
| 38 | + if (environment !== 'production') { |
| 39 | + logger.info('Skipping discord notification non production environment!'); |
| 40 | + return; |
| 41 | + } |
| 42 | + let params: DiscordMessage; |
| 43 | + if (object === null) { |
| 44 | + params = { username: botUsername, content: msg }; |
| 45 | + } else { |
| 46 | + params = { |
| 47 | + username: botUsername, |
| 48 | + content: msg, |
| 49 | + embeds: [{ title: msg, description: JSON.stringify(object) }], |
| 50 | + }; |
| 51 | + } |
| 52 | + const res = await httpClient(discordUrl, { |
| 53 | + method: 'POST', |
| 54 | + headers: { 'Content-Type': 'application/json' }, |
| 55 | + body: JSON.stringify(params), |
| 56 | + }); |
| 57 | + if (res.status === 204) { |
| 58 | + logger.info(`Discord bot has sent: ${msg}`); |
| 59 | + } else { |
| 60 | + throw new Error(`Discord API returned status ${res.status}`); |
| 61 | + } |
| 62 | + } catch (error) { |
| 63 | + console.error('Error sending Discord notification:', error); |
| 64 | + } |
| 65 | + }, |
| 66 | + email: async (to: string, subject: string, body: string): Promise<void> => { |
| 67 | + try { |
| 68 | + console.log('notify.email() has not been implemented yet'); |
| 69 | + } catch (error) { |
| 70 | + console.error('Error sending email notification:', error); |
| 71 | + } |
| 72 | + }, |
| 73 | + }; |
| 74 | +} |
0 commit comments