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

64 lines
2.0 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 https from 'https';
import { z } from 'zod';
import { isStatusOk } from '~/components/Dashboard/Tiles/Apps/AppPing';
2023-06-14 17:31:52 +09:00
import { getConfig } from '~/tools/config/getConfig';
import { AppType } from '~/types/app';
2023-06-10 10:23:54 +02:00
import { createTRPCRouter, publicProcedure } from '../trpc';
export const appRouter = createTRPCRouter({
ping: publicProcedure.input(z.object({
id: z.string(),
configName: z.string()
})).query(async ({ input }) => {
2023-06-14 17:31:52 +09:00
const agent = new https.Agent({ rejectUnauthorized: false });
const config = getConfig(input.configName);
const app = config.apps.find((app) => app.id === input.id);
2023-07-17 21:35:34 +02:00
if (!app?.url) {
2023-07-17 21:35:34 +02:00
Consola.error(`App ${input} not found`);
2023-07-22 10:11:23 +09:00
throw new TRPCError({
code: 'NOT_FOUND',
cause: input,
message: `App ${input.id} was not found`,
2023-07-22 10:11:23 +09:00
});
2023-06-14 17:31:52 +09:00
}
const res = await axios
.get(app.url, { httpsAgent: agent, timeout: 10000 })
2023-06-14 17:31:52 +09:00
.then((response) => ({
status: response.status,
statusText: response.statusText,
state: isStatusOk(app as AppType, response.status) ? 'online' : 'offline'
2023-06-14 17:31:52 +09:00
}))
.catch((error: AxiosError) => {
if (error.response) {
2023-07-17 21:35:34 +02:00
return {
state: isStatusOk(app as AppType, error.response.status) ? 'online' : 'offline',
2023-07-17 21:35:34 +02:00
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') {
Consola.error(`Ping timed out for app with id : ${input} (url: ${app.url})`);
2023-07-22 10:11:23 +09:00
throw new TRPCError({
code: 'TIMEOUT',
cause: input,
message: `Ping timed out`,
});
2023-06-14 17:31:52 +09:00
}
Consola.error(`Unexpected response: ${error.message}`);
2023-07-22 10:11:23 +09:00
throw new TRPCError({
code: 'UNPROCESSABLE_CONTENT',
cause: input,
message: `Unexpected response: ${error.message}`,
});
2023-06-14 17:31:52 +09:00
});
return res;
}),
2023-06-10 10:23:54 +02:00
});