|
| 1 | +import {Link, Store} from '../store/model'; |
| 2 | +import {Print, logger} from '../logger'; |
| 3 | +import {config} from '../config'; |
| 4 | +import fetch from 'node-fetch'; |
| 5 | + |
| 6 | +const {ntfy} = config.notifications; |
| 7 | + |
| 8 | +export function sendNtfyAlert(link: Link, store: Store) { |
| 9 | + if (ntfy.topic) { |
| 10 | + logger.debug('↗ sending ntfy alert'); |
| 11 | + |
| 12 | + (async () => { |
| 13 | + const message = `${Print.inStock(link, store)}`; |
| 14 | + const headers: Record<string, string> = {}; |
| 15 | + |
| 16 | + if (ntfy.priority) headers['Priority'] = ntfy.priority; |
| 17 | + headers[ |
| 18 | + 'Tags' |
| 19 | + ] = `${store.name},${link.model},${link.series},${link.brand}`; |
| 20 | + if (ntfy.title) headers['Title'] = ntfy.title; |
| 21 | + if (ntfy.accessToken) |
| 22 | + headers['Authorization'] = `Bearer ${ntfy.accessToken}`; |
| 23 | + |
| 24 | + const body = { |
| 25 | + topic: ntfy.topic, |
| 26 | + message, |
| 27 | + actions: [ |
| 28 | + { |
| 29 | + action: 'view', |
| 30 | + label: 'Add to cart', |
| 31 | + url: link.cartUrl ?? link.url, |
| 32 | + }, |
| 33 | + ], |
| 34 | + }; |
| 35 | + |
| 36 | + try { |
| 37 | + const response = await fetch(ntfy.url, { |
| 38 | + method: 'POST', |
| 39 | + body: JSON.stringify(body), |
| 40 | + headers: { |
| 41 | + ...headers, |
| 42 | + 'Content-Type': 'application/json', |
| 43 | + }, |
| 44 | + }); |
| 45 | + |
| 46 | + if (!response.ok) |
| 47 | + throw new Error(`Failed to send ntfy alert: ${response.statusText}`); |
| 48 | + |
| 49 | + logger.info('✔ ntfy alert sent'); |
| 50 | + } catch (error: unknown) { |
| 51 | + logger.error("✖ couldn't send ntfy alert", error); |
| 52 | + } |
| 53 | + })(); |
| 54 | + } |
| 55 | +} |
0 commit comments