refactor(server): update server configuration handling to utilize webServerSettings schema and improve code clarity

This commit is contained in:
Mauricio Siu
2025-12-21 01:41:33 -06:00
parent 1ccb205495
commit 6010643d9e
5 changed files with 57 additions and 59 deletions
@@ -5,21 +5,27 @@ vi.mock("node:fs", () => ({
default: fs, default: fs,
})); }));
import type { FileConfig, User } from "@dokploy/server"; import type { FileConfig } from "@dokploy/server";
import { import {
createDefaultServerTraefikConfig, createDefaultServerTraefikConfig,
loadOrCreateConfig, loadOrCreateConfig,
updateServerTraefik, updateServerTraefik,
} from "@dokploy/server"; } from "@dokploy/server";
import type { webServerSettings } from "@dokploy/server/db/schema";
import { beforeEach, expect, test, vi } from "vitest"; import { beforeEach, expect, test, vi } from "vitest";
const baseAdmin: User = { type WebServerSettings = typeof webServerSettings.$inferSelect;
const baseSettings: WebServerSettings = {
id: "",
https: false, https: false,
enablePaidFeatures: false, certificateType: "none",
allowImpersonation: false, host: null,
role: "user", serverIp: null,
firstName: "", letsEncryptEmail: null,
lastName: "", sshPrivateKey: null,
enableDockerCleanup: false,
logCleanupCron: null,
metricsConfig: { metricsConfig: {
containers: { containers: {
refreshRate: 20, refreshRate: 20,
@@ -45,29 +51,8 @@ const baseAdmin: User = {
cleanupCacheApplications: false, cleanupCacheApplications: false,
cleanupCacheOnCompose: false, cleanupCacheOnCompose: false,
cleanupCacheOnPreviews: false, cleanupCacheOnPreviews: false,
createdAt: new Date(), createdAt: null,
serverIp: null,
certificateType: "none",
host: null,
letsEncryptEmail: null,
sshPrivateKey: null,
enableDockerCleanup: false,
logCleanupCron: null,
serversQuantity: 0,
stripeCustomerId: "",
stripeSubscriptionId: "",
banExpires: new Date(),
banned: true,
banReason: "",
email: "",
expirationDate: "",
id: "",
isRegistered: false,
createdAt2: new Date().toISOString(),
emailVerified: false,
image: "",
updatedAt: new Date(), updatedAt: new Date(),
twoFactorEnabled: false,
}; };
beforeEach(() => { beforeEach(() => {
@@ -85,7 +70,7 @@ test("Should read the configuration file", () => {
test("Should apply redirect-to-https", () => { test("Should apply redirect-to-https", () => {
updateServerTraefik( updateServerTraefik(
{ {
...baseAdmin, ...baseSettings,
https: true, https: true,
certificateType: "letsencrypt", certificateType: "letsencrypt",
}, },
@@ -100,7 +85,7 @@ test("Should apply redirect-to-https", () => {
}); });
test("Should change only host when no certificate", () => { test("Should change only host when no certificate", () => {
updateServerTraefik(baseAdmin, "example.com"); updateServerTraefik(baseSettings, "example.com");
const config: FileConfig = loadOrCreateConfig("dokploy"); const config: FileConfig = loadOrCreateConfig("dokploy");
@@ -110,7 +95,7 @@ test("Should change only host when no certificate", () => {
test("Should not touch config without host", () => { test("Should not touch config without host", () => {
const originalConfig: FileConfig = loadOrCreateConfig("dokploy"); const originalConfig: FileConfig = loadOrCreateConfig("dokploy");
updateServerTraefik(baseAdmin, null); updateServerTraefik(baseSettings, null);
const config: FileConfig = loadOrCreateConfig("dokploy"); const config: FileConfig = loadOrCreateConfig("dokploy");
@@ -119,11 +104,14 @@ test("Should not touch config without host", () => {
test("Should remove websecure if https rollback to http", () => { test("Should remove websecure if https rollback to http", () => {
updateServerTraefik( updateServerTraefik(
{ ...baseAdmin, certificateType: "letsencrypt" }, { ...baseSettings, certificateType: "letsencrypt" },
"example.com", "example.com",
); );
updateServerTraefik({ ...baseAdmin, certificateType: "none" }, "example.com"); updateServerTraefik(
{ ...baseSettings, certificateType: "none" },
"example.com",
);
const config: FileConfig = loadOrCreateConfig("dokploy"); const config: FileConfig = loadOrCreateConfig("dokploy");
@@ -80,7 +80,7 @@ const Schema = z.object({
type Schema = z.infer<typeof Schema>; type Schema = z.infer<typeof Schema>;
export const SetupMonitoring = ({ serverId }: Props) => { export const SetupMonitoring = ({ serverId }: Props) => {
const { data } = serverId const { data: serverData } = serverId
? api.server.one.useQuery( ? api.server.one.useQuery(
{ {
serverId: serverId || "", serverId: serverId || "",
@@ -89,7 +89,14 @@ export const SetupMonitoring = ({ serverId }: Props) => {
enabled: !!serverId, enabled: !!serverId,
}, },
) )
: api.user.getServerMetrics.useQuery(); : { data: null };
const { data: webServerSettings } =
api.settings.getWebServerSettings.useQuery(undefined, {
enabled: !serverId,
});
const data = serverId ? serverData : webServerSettings;
const url = useUrl(); const url = useUrl();
+13 -7
View File
@@ -17,8 +17,8 @@ import {
findGitProviderById, findGitProviderById,
findProjectById, findProjectById,
findServerById, findServerById,
findUserById,
getComposeContainer, getComposeContainer,
getWebServerSettings,
IS_CLOUD, IS_CLOUD,
loadServices, loadServices,
randomizeComposeFile, randomizeComposeFile,
@@ -569,8 +569,7 @@ export const composeRouter = createTRPCRouter({
const template = await fetchTemplateFiles(input.id, input.baseUrl); const template = await fetchTemplateFiles(input.id, input.baseUrl);
const admin = await findUserById(ctx.user.ownerId); let serverIp = "127.0.0.1";
let serverIp = admin.serverIp || "127.0.0.1";
const project = await findProjectById(environment.projectId); const project = await findProjectById(environment.projectId);
@@ -579,6 +578,9 @@ export const composeRouter = createTRPCRouter({
serverIp = server.ipAddress; serverIp = server.ipAddress;
} else if (process.env.NODE_ENV === "development") { } else if (process.env.NODE_ENV === "development") {
serverIp = "127.0.0.1"; serverIp = "127.0.0.1";
} else {
const settings = await getWebServerSettings();
serverIp = settings?.serverIp || "127.0.0.1";
} }
const projectName = slugify(`${project.name} ${input.id}`); const projectName = slugify(`${project.name} ${input.id}`);
@@ -803,14 +805,16 @@ export const composeRouter = createTRPCRouter({
const decodedData = Buffer.from(input.base64, "base64").toString( const decodedData = Buffer.from(input.base64, "base64").toString(
"utf-8", "utf-8",
); );
const admin = await findUserById(ctx.user.ownerId); let serverIp = "127.0.0.1";
let serverIp = admin.serverIp || "127.0.0.1";
if (compose.serverId) { if (compose.serverId) {
const server = await findServerById(compose.serverId); const server = await findServerById(compose.serverId);
serverIp = server.ipAddress; serverIp = server.ipAddress;
} else if (process.env.NODE_ENV === "development") { } else if (process.env.NODE_ENV === "development") {
serverIp = "127.0.0.1"; serverIp = "127.0.0.1";
} else {
const settings = await getWebServerSettings();
serverIp = settings?.serverIp || "127.0.0.1";
} }
const templateData = JSON.parse(decodedData); const templateData = JSON.parse(decodedData);
const config = parse(templateData.config) as CompleteTemplate; const config = parse(templateData.config) as CompleteTemplate;
@@ -880,14 +884,16 @@ export const composeRouter = createTRPCRouter({
await removeDomainById(domain.domainId); await removeDomainById(domain.domainId);
} }
const admin = await findUserById(ctx.user.ownerId); let serverIp = "127.0.0.1";
let serverIp = admin.serverIp || "127.0.0.1";
if (compose.serverId) { if (compose.serverId) {
const server = await findServerById(compose.serverId); const server = await findServerById(compose.serverId);
serverIp = server.ipAddress; serverIp = server.ipAddress;
} else if (process.env.NODE_ENV === "development") { } else if (process.env.NODE_ENV === "development") {
serverIp = "127.0.0.1"; serverIp = "127.0.0.1";
} else {
const settings = await getWebServerSettings();
serverIp = settings?.serverIp || "127.0.0.1";
} }
const templateData = JSON.parse(decodedData); const templateData = JSON.parse(decodedData);
+4 -6
View File
@@ -9,6 +9,7 @@ import {
findPreviewDeploymentById, findPreviewDeploymentById,
findServerById, findServerById,
generateTraefikMeDomain, generateTraefikMeDomain,
getWebServerSettings,
manageDomain, manageDomain,
removeDomain, removeDomain,
removeDomainById, removeDomainById,
@@ -107,16 +108,13 @@ export const domainRouter = createTRPCRouter({
}), }),
canGenerateTraefikMeDomains: protectedProcedure canGenerateTraefikMeDomains: protectedProcedure
.input(z.object({ serverId: z.string() })) .input(z.object({ serverId: z.string() }))
.query(async ({ input, ctx }) => { .query(async ({ input }) => {
const organization = await findOrganizationById(
ctx.session.activeOrganizationId,
);
if (input.serverId) { if (input.serverId) {
const server = await findServerById(input.serverId); const server = await findServerById(input.serverId);
return server.ipAddress; return server.ipAddress;
} }
return organization?.owner.serverIp; const settings = await getWebServerSettings();
return settings?.serverIp || "";
}), }),
update: protectedProcedure update: protectedProcedure
@@ -8,6 +8,7 @@ import {
createSlackNotification, createSlackNotification,
createTelegramNotification, createTelegramNotification,
findNotificationById, findNotificationById,
getWebServerSettings,
IS_CLOUD, IS_CLOUD,
removeNotificationById, removeNotificationById,
sendCustomNotification, sendCustomNotification,
@@ -66,7 +67,6 @@ import {
apiUpdateTelegram, apiUpdateTelegram,
notifications, notifications,
server, server,
user,
} from "@/server/db/schema"; } from "@/server/db/schema";
export const notificationRouter = createTRPCRouter({ export const notificationRouter = createTRPCRouter({
@@ -364,21 +364,20 @@ export const notificationRouter = createTRPCRouter({
let organizationId = ""; let organizationId = "";
let ServerName = ""; let ServerName = "";
if (input.ServerType === "Dokploy") { if (input.ServerType === "Dokploy") {
const result = await db const settings = await getWebServerSettings();
.select() if (
.from(user) !settings?.metricsConfig?.server?.token ||
.where( settings.metricsConfig.server.token !== input.Token
sql`${user.metricsConfig}::jsonb -> 'server' ->> 'token' = ${input.Token}`, ) {
);
if (!result?.[0]?.id) {
throw new TRPCError({ throw new TRPCError({
code: "BAD_REQUEST", code: "BAD_REQUEST",
message: "Token not found", message: "Token not found",
}); });
} }
organizationId = result?.[0]?.id; // For Dokploy server type, we don't have a specific organizationId
// This might need to be adjusted based on your business logic
organizationId = "";
ServerName = "Dokploy"; ServerName = "Dokploy";
} else { } else {
const result = await db const result = await db