Files
Homarr/src/server/api/routers/app.ts

57 lines
1.8 KiB
TypeScript
Raw Normal View History

2023-06-14 17:31:52 +09:00
import { TRPCError } from '@trpc/server';
2023-06-10 10:23:54 +02:00
import axios, { AxiosError } from 'axios';
import Consola from 'consola';
2023-06-14 17:31:52 +09:00
import { getCookie } from 'cookies-next';
import https from 'https';
import { z } from 'zod';
import { getIsOk } from '~/components/Dashboard/Tiles/Apps/AppPing';
import { getConfig } from '~/tools/config/getConfig';
import { AppType } from '~/types/app';
2023-06-10 10:23:54 +02:00
import { createTRPCRouter, publicProcedure } from '../trpc';
2023-07-18 07:23:17 +02:00
const errorResponse = {
2023-07-21 18:08:40 +09:00
state: 'offline',
status: 500,
statusText: 'Check logs for more informations',
2023-07-18 07:23:17 +02:00
};
2023-06-10 10:23:54 +02:00
export const appRouter = createTRPCRouter({
2023-06-14 17:31:52 +09:00
ping: publicProcedure.input(z.string()).query(async ({ input }) => {
const agent = new https.Agent({ rejectUnauthorized: false });
const configName = getCookie('config-name');
const config = getConfig(configName?.toString() ?? 'default');
const app = config.apps.find((app) => app.id === input);
2023-07-17 21:35:34 +02:00
2023-06-14 17:31:52 +09:00
const url = app?.url;
if (url === undefined || !app) {
2023-07-17 21:35:34 +02:00
Consola.error(`App ${input} not found`);
return errorResponse;
2023-06-14 17:31:52 +09:00
}
const res = await axios
.get(url, { httpsAgent: agent, timeout: 2000 })
.then((response) => ({
status: response.status,
statusText: response.statusText,
}))
.catch((error: AxiosError) => {
if (error.response) {
2023-07-17 21:35:34 +02:00
return {
state: getIsOk(app as AppType, error.response.status) ? 'online' : 'offline',
status: error.response.status,
statusText: error.response.statusText,
};
2023-06-14 17:31:52 +09:00
}
2023-07-17 21:35:34 +02:00
2023-06-14 17:31:52 +09:00
if (error.code === 'ECONNABORTED') {
2023-07-17 21:35:34 +02:00
Consola.error(`Ping timeout for ${input}`);
return errorResponse;
2023-06-14 17:31:52 +09:00
}
Consola.error(`Unexpected response: ${error.message}`);
2023-07-17 21:35:34 +02:00
return errorResponse;
2023-06-14 17:31:52 +09:00
});
return res;
}),
2023-06-10 10:23:54 +02:00
});