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';
|
|
|
|
|
|
|
|
|
|
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);
|
|
|
|
|
const url = app?.url;
|
|
|
|
|
if (url === undefined || !app) {
|
|
|
|
|
throw new TRPCError({
|
|
|
|
|
code: 'NOT_FOUND',
|
|
|
|
|
message: 'App or url not found',
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
const res = await axios
|
|
|
|
|
.get(url, { httpsAgent: agent, timeout: 2000 })
|
|
|
|
|
.then((response) => ({
|
|
|
|
|
status: response.status,
|
|
|
|
|
statusText: response.statusText,
|
|
|
|
|
}))
|
|
|
|
|
.catch((error: AxiosError) => {
|
|
|
|
|
if (error.response) {
|
|
|
|
|
if (getIsOk(app as AppType, error.response.status)) {
|
2023-06-10 10:23:54 +02:00
|
|
|
return {
|
2023-06-14 17:31:52 +09:00
|
|
|
state: 'offline',
|
2023-06-10 10:23:54 +02:00
|
|
|
status: error.response.status,
|
|
|
|
|
statusText: error.response.statusText,
|
|
|
|
|
};
|
|
|
|
|
}
|
2023-06-14 17:31:52 +09:00
|
|
|
}
|
|
|
|
|
if (error.code === 'ECONNABORTED') {
|
2023-06-10 10:23:54 +02:00
|
|
|
throw new TRPCError({
|
2023-06-14 17:31:52 +09:00
|
|
|
code: 'TIMEOUT',
|
|
|
|
|
message: 'Request Timeout',
|
2023-06-10 10:23:54 +02:00
|
|
|
});
|
2023-06-14 17:31:52 +09:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
Consola.error(`Unexpected response: ${error.message}`);
|
|
|
|
|
throw new TRPCError({
|
|
|
|
|
code: 'INTERNAL_SERVER_ERROR',
|
|
|
|
|
cause: app.id,
|
|
|
|
|
message: error.message,
|
2023-06-10 10:23:54 +02:00
|
|
|
});
|
2023-06-14 17:31:52 +09:00
|
|
|
});
|
|
|
|
|
return res;
|
|
|
|
|
}),
|
2023-06-10 10:23:54 +02:00
|
|
|
});
|