Skip to content

Modern Docker Management, Designed for Everyone

2.5 KB
Raw Blame
import type { QueryClient } from '@tanstack/svelte-query';

import { queryKeys } from '#lib/query/query-keys.js';
import { projectService } from '#lib/services/project-service.js';
import { projectWorkspaceService } from '#lib/services/project-workspace-service.js';
import { variableService } from '#lib/services/variable-service.js';
import { throwPageLoadError } from '#lib/utils/api.js';
import { resolveDetailEnvironmentId } from '#lib/utils/environments.js';
import { tryCatch } from '#lib/utils/try-catch.js';

import type { PageLoad } from './$types';

async function loadGlobalVariables(queryClient: QueryClient) {
	return tryCatch(
		queryClient.query({
			queryKey: queryKeys.variables.list(),
			queryFn: () => variableService.list()
		})
	).then((result) => {
		if (result.error) {
			const err: Error = result.error;

			console.warn('Failed to load global variables:', err);
			return [];
		}
		return result.data;
	});
}

export const load: PageLoad = async ({ params, parent, url }) => {
	const { queryClient } = await parent();
	const envId = await resolveDetailEnvironmentId(url);

	type ProjectData = Awaited<ReturnType<typeof projectService.getProjectForEnvironment>>;

	let project: ProjectData;
	const operationResult = await tryCatch(
		(async () =>
			queryClient.query({
				queryKey: queryKeys.projects.detail(envId, params.projectId),
				queryFn: () => projectService.getProjectForEnvironment(envId, params.projectId)
			}))()
	);
	if (operationResult.error !== null) {
		const err = operationResult.error;

		throwPageLoadError(err, 'Failed to load project');
	} else {
		project = operationResult.data;
	}

	// Kick off the file-tree walk without awaiting it: on large projects it can
	// take a while and must not block navigation.
	void queryClient.prefetchQuery({
		queryKey: queryKeys.projects.workspace(envId, params.projectId),
		queryFn: () => projectWorkspaceService.getWorkspace(params.projectId, envId)
	});

	const globalVariables = await loadGlobalVariables(queryClient);

	const editorState = {
		name: project.name || '',
		composeContent: project.composeContent || '',
		envContent: project.envContent || '',
		overrideContent: project.overrideContent || '',
		originalName: project.name || '',
		originalComposeContent: project.composeContent || '',
		originalEnvContent: project.envContent || '',
		originalOverrideContent: project.overrideContent || ''
	};

	return {
		envId,
		projectId: params.projectId,
		project,
		editorState,
		globalVariables,
		error: null as string | null
	};
};