Luncher/server/src/notifikace.ts
Martin Berka 3c0e8b2297 Deduplikace typů a sloučení kontejnerů
- Zavedení yarn workspaces
- Sloučení klienta a serveru do jednoho Docker kontejneru
- Společný dockerfile, builder
- Zbavení se nginx (není již potřeba)
2023-07-22 19:37:03 +02:00

77 lines
2.6 KiB
TypeScript

/** Notifikace pro gotify*/
import { GotifyServer, NotififaceInput, NotifikaceData } from '../../types';
import axios, { AxiosError } from 'axios';
import dotenv from 'dotenv';
import path from 'path';
const ENVIRONMENT = process.env.NODE_ENV || 'production'
dotenv.config({ path: path.resolve(__dirname, `../.env.${ENVIRONMENT}`) });
const gotifyDataRaw = process.env.GOTIFY_SERVERS_AND_KEYS || "{}";
const gotifyData: GotifyServer[] = JSON.parse(gotifyDataRaw);
export const gotifyCall = async (data: NotififaceInput, gotifyServers?: GotifyServer[]): Promise<any[]> => {
if (!Array.isArray(gotifyServers)) {
return []
}
const urls = gotifyServers.flatMap(gotifyServer =>
gotifyServer.api_keys.map(apiKey => `${gotifyServer.server}/message?token=${apiKey}`));
const dataPayload = {
title: "Luncher",
message: `${data.udalost} - spustil:${data.user}`,
priority: 7,
};
const headers = { "Content-Type": "application/json" };
const promises = urls.map(url =>
axios.post(url, dataPayload, { headers }).then(response => {
response.data = {
success: true,
message: "Notifikace doručena",
};
return response;
}).catch(error => {
if (axios.isAxiosError(error)) {
const axiosError = error as AxiosError;
if (axiosError.response) {
axiosError.response.data = {
success: false,
message: "fail",
};
console.log(error)
return axiosError.response;
}
}
// Handle unknown error without a response
console.log(error, "unknown error");
})
);
return promises;
};
/** Zavolá notifikace na všechny konfigurované způsoby notifikace, přetížení proměných na false pro jednotlivé způsoby je vypne*/
export const callNotifikace = async ({ input, teams = true, gotify = true }: NotifikaceData) => {
const notifications = [];
if (gotify) {
const gotifyPromises = await gotifyCall(input, gotifyData);
notifications.push(...gotifyPromises);
}
/* Zatím není
if (teams) {
notifications.push(teamsCall(input));
}*/
// Add more notifications as necessary
try {
const results = await Promise.all(notifications);
return results;
} catch (error) {
console.error("Error in callNotifikace: ", error);
// Handle the error as needed
}
};