autobaan/src/ntfy/client.ts

49 lines
1.2 KiB
TypeScript
Raw Normal View History

2023-09-05 09:12:04 +02:00
import { Inject, Injectable } from '@nestjs/common'
import { ConfigService } from '@nestjs/config'
import { Axios } from 'axios'
import { LoggerService } from '../logger/service.logger'
2023-09-05 09:12:04 +02:00
import { MessageConfig } from './types'
@Injectable()
export class NtfyClient {
private readonly httpClient: Axios
private readonly topic: string
constructor(
@Inject(ConfigService)
private readonly configService: ConfigService,
@Inject(LoggerService)
private readonly loggerService: LoggerService,
2023-09-05 09:12:04 +02:00
) {
const host = this.configService.getOrThrow<string>('NTFY_HOST')
this.topic = this.configService.getOrThrow<string>('NTFY_TOPIC')
2023-09-13 20:52:25 +02:00
const token = this.configService.getOrThrow<string>('NTFY_TOKEN')
2023-09-05 09:12:04 +02:00
this.httpClient = new Axios({
baseURL: `https://${host}`,
headers: {
'Content-Type': 'application/json',
2023-09-13 20:52:25 +02:00
Authorization: `Bearer ${token}`,
2023-09-05 09:12:04 +02:00
},
})
}
async publish(message: Omit<MessageConfig, 'topic'>) {
try {
await this.httpClient.post(
'/',
JSON.stringify({
topic: this.topic,
...message,
}),
)
2024-09-19 12:51:21 +02:00
this.loggerService.debug('Published ntfy-cation', {
topic: this.topic,
message,
})
} catch (error: unknown) {
this.loggerService.error('ntfy client failed', { error })
}
2023-09-05 09:12:04 +02:00
}
}