refactor: simplify file checks

This commit is contained in:
Carlos Valente
2024-07-02 18:01:51 +02:00
committed by Carlos Valente
parent 751c3329f0
commit 367997fd16
4 changed files with 41 additions and 45 deletions
+3 -8
View File
@@ -8,13 +8,10 @@ import {
} from 'ontime-types'; } from 'ontime-types';
import { getErrorMessage } from 'ontime-utils'; import { getErrorMessage } from 'ontime-utils';
import { join } from 'path';
import { existsSync } from 'fs';
import type { Request, Response } from 'express'; import type { Request, Response } from 'express';
import { failEmptyObjects } from '../../utils/routerUtils.js'; import { failEmptyObjects } from '../../utils/routerUtils.js';
import { resolveDbDirectory } from '../../setup/index.js'; import { doesProjectExist, handleUploaded } from '../../services/project-service/projectServiceUtils.js';
import { handleUploaded } from '../../services/project-service/projectServiceUtils.js';
import * as projectService from '../../services/project-service/ProjectService.js'; import * as projectService from '../../services/project-service/ProjectService.js';
export async function patchPartialProjectFile(req: Request, res: Response<DatabaseModel | ErrorResponse>) { export async function patchPartialProjectFile(req: Request, res: Response<DatabaseModel | ErrorResponse>) {
@@ -73,10 +70,8 @@ export async function createProjectFile(req: Request, res: Response<{ filename:
*/ */
export async function projectDownload(req: Request, res: Response) { export async function projectDownload(req: Request, res: Response) {
const { filename } = req.body; const { filename } = req.body;
const pathToFile = join(resolveDbDirectory, filename); const pathToFile = await doesProjectExist(filename);
if (!pathToFile) {
// Check if the file exists before attempting to download
if (!existsSync(pathToFile)) {
return res.status(404).send({ message: `Project ${filename} not found.` }); return res.status(404).send({ message: `Project ${filename} not found.` });
} }
@@ -37,12 +37,11 @@ function init() {
* Loads a data from a file into the runtime * Loads a data from a file into the runtime
*/ */
export async function loadProjectFile(name: string) { export async function loadProjectFile(name: string) {
if (!(await doesProjectExist(name))) { const filePath = await doesProjectExist(name);
if (filePath === null) {
throw new Error('Project file not found'); throw new Error('Project file not found');
} }
const filePath = getPathToProject(name);
// when loading a project file, we allow parsing to fail and interrupt the process // when loading a project file, we allow parsing to fail and interrupt the process
const fileData = await parseProjectFile(filePath); const fileData = await parseProjectFile(filePath);
const result = parseJson(fileData); const result = parseJson(fileData);
@@ -96,45 +95,45 @@ export async function getProjectList(): Promise<ProjectFileListResponse> {
* Duplicates an existing project file * Duplicates an existing project file
*/ */
export async function duplicateProjectFile(originalFile: string, newFilename: string) { export async function duplicateProjectFile(originalFile: string, newFilename: string) {
if (!(await doesProjectExist(originalFile))) { const projectFilePath = await doesProjectExist(originalFile);
if (projectFilePath === null) {
throw new Error('Project file not found'); throw new Error('Project file not found');
} }
if (await doesProjectExist(newFilename)) { const duplicateProjectFilePath = await doesProjectExist(newFilename);
if (duplicateProjectFilePath !== null) {
throw new Error(`Project file with name ${newFilename} already exists`); throw new Error(`Project file with name ${newFilename} already exists`);
} }
const projectFilePath = getPathToProject(originalFile); const pathToDuplicate = getPathToProject(newFilename);
const duplicateProjectFilePath = getPathToProject(newFilename); return copyFile(projectFilePath, pathToDuplicate);
return copyFile(projectFilePath, duplicateProjectFilePath);
} }
/** /**
* Renames an existing project file * Renames an existing project file
*/ */
export async function renameProjectFile(originalFile: string, newFilename: string) { export async function renameProjectFile(originalFile: string, newFilename: string) {
if (!(await doesProjectExist(originalFile))) { const projectFilePath = await doesProjectExist(originalFile);
if (projectFilePath === null) {
throw new Error('Project file not found'); throw new Error('Project file not found');
} }
if (await doesProjectExist(newFilename)) { const newProjectFilePath = await doesProjectExist(newFilename);
if (newProjectFilePath !== null) {
throw new Error(`Project file with name ${newFilename} already exists`); throw new Error(`Project file with name ${newFilename} already exists`);
} }
const projectFilePath = getPathToProject(originalFile); const pathToRenamed = getPathToProject(newFilename);
const newProjectFilePath = getPathToProject(newFilename); await rename(projectFilePath, pathToRenamed);
await rename(projectFilePath, newProjectFilePath);
// Update the last loaded project config if current loaded project is the one being renamed // Update the last loaded project config if current loaded project is the one being renamed
const isLoaded = await appStateProvider.isLastLoadedProject(originalFile); const isLoaded = await appStateProvider.isLastLoadedProject(originalFile);
if (isLoaded) { if (isLoaded) {
const fileData = await parseProjectFile(newProjectFilePath); const fileData = await parseProjectFile(pathToRenamed);
const result = parseJson(fileData); const result = parseJson(fileData);
// change LowDB to point to new file // change LowDB to point to new file
await switchDb(newProjectFilePath, result.data); await switchDb(pathToRenamed, result.data);
logger.info(LogOrigin.Server, `Loaded project ${newFilename}`); logger.info(LogOrigin.Server, `Loaded project ${newFilename}`);
// persist the project selection // persist the project selection
@@ -191,11 +190,11 @@ export async function deleteProjectFile(filename: string) {
throw new Error('Cannot delete currently loaded project'); throw new Error('Cannot delete currently loaded project');
} }
if (!(await doesProjectExist(filename))) { const projectFilePath = await doesProjectExist(filename);
if (projectFilePath === null) {
throw new Error('Project file not found'); throw new Error('Project file not found');
} }
const projectFilePath = getPathToProject(filename);
await deleteFile(projectFilePath); await deleteFile(projectFilePath);
} }
@@ -1,8 +1,10 @@
import { deleteProjectFile, duplicateProjectFile, renameProjectFile } from '../ProjectService.js';
import { appStateProvider } from '../../app-state-service/AppStateService.js';
import { doesProjectExist } from '../projectServiceUtils.js';
import { Mock } from 'vitest'; import { Mock } from 'vitest';
import { appStateProvider } from '../../app-state-service/AppStateService.js';
import { deleteProjectFile, duplicateProjectFile, renameProjectFile } from '../ProjectService.js';
import { doesProjectExist } from '../projectServiceUtils.js';
// stop the database loading from initiating // stop the database loading from initiating
vi.mock('../../../setup/loadDb.js', () => { vi.mock('../../../setup/loadDb.js', () => {
return { return {
@@ -33,23 +35,23 @@ describe('deleteProjectFile', () => {
it('throws an error if the project file does not exist', async () => { it('throws an error if the project file does not exist', async () => {
(appStateProvider.isLastLoadedProject as Mock).mockResolvedValue(false); (appStateProvider.isLastLoadedProject as Mock).mockResolvedValue(false);
(doesProjectExist as Mock).mockReturnValue(false); (doesProjectExist as Mock).mockReturnValue(null);
await expect(deleteProjectFile('nonexistentProject')).rejects.toThrow('Project file not found'); await expect(deleteProjectFile('nonexistentProject')).rejects.toThrow('Project file not found');
}); });
}); });
describe('duplicateProjectFile', () => { describe('duplicateProjectFile', () => {
it('throws an error if origin project does not exist', async () => { it('throws an error if origin project does not exist', async () => {
(doesProjectExist as Mock).mockReturnValue(false); (doesProjectExist as Mock).mockReturnValue(null);
await expect(duplicateProjectFile('does not exist', 'doesnt matter')).rejects.toThrow('Project file not found'); await expect(duplicateProjectFile('does not exist', 'doesnt matter')).rejects.toThrow('Project file not found');
}); });
it('throws an error if new file name is already a project', async () => { it('throws an error if new file name is already a project', () => {
// current project exists // current project exists
(doesProjectExist as Mock).mockReturnValueOnce(true); (doesProjectExist as Mock).mockReturnValueOnce('thisoneexists');
// new project exists // new project exists
(doesProjectExist as Mock).mockReturnValueOnce(true); (doesProjectExist as Mock).mockReturnValueOnce('existingproject');
expect(duplicateProjectFile('nonexistentProject', 'existingproject')).rejects.toThrow( expect(duplicateProjectFile('thisoneexists', 'existingproject')).rejects.toThrow(
'Project file with name existingproject already exists', 'Project file with name existingproject already exists',
); );
}); });
@@ -57,16 +59,16 @@ describe('duplicateProjectFile', () => {
describe('renameProjectFile', () => { describe('renameProjectFile', () => {
it('throws an error if origin project does not exist', async () => { it('throws an error if origin project does not exist', async () => {
(doesProjectExist as Mock).mockReturnValue(false); (doesProjectExist as Mock).mockReturnValue(null);
await expect(renameProjectFile('does not exist', 'doesnt matter')).rejects.toThrow('Project file not found'); await expect(renameProjectFile('does not exist', 'doesnt matter')).rejects.toThrow('Project file not found');
}); });
it('throws an error if new file name is already a project', async () => { it('throws an error if new file name is already a project', async () => {
// current project exists // current project exists
(doesProjectExist as Mock).mockReturnValueOnce(true); (doesProjectExist as Mock).mockReturnValueOnce('this one exists');
// new project exists // new project exists
(doesProjectExist as Mock).mockReturnValueOnce(true); (doesProjectExist as Mock).mockReturnValueOnce('existingproject');
expect(renameProjectFile('nonexistentProject', 'existingproject')).rejects.toThrow( expect(renameProjectFile('this one exists', 'existingproject')).rejects.toThrow(
'Project file with name existingproject already exists', 'Project file with name existingproject already exists',
); );
}); });
@@ -1,4 +1,4 @@
import { ProjectFile } from 'ontime-types'; import { MaybeString, ProjectFile } from 'ontime-types';
import { access, rename, stat } from 'fs/promises'; import { access, rename, stat } from 'fs/promises';
import { join } from 'path'; import { join } from 'path';
@@ -51,13 +51,13 @@ export async function getProjectFiles(): Promise<ProjectFile[]> {
* Checks whether a project of a given name exists * Checks whether a project of a given name exists
* @param name * @param name
*/ */
export async function doesProjectExist(name: string): Promise<boolean> { export async function doesProjectExist(name: string): Promise<MaybeString> {
try { try {
const projectFilePath = join(resolveProjectsDirectory, name); const projectFilePath = getPathToProject(name);
await access(projectFilePath); await access(projectFilePath);
return true; return projectFilePath;
} catch (_) { } catch (_) {
return false; return null;
} }
} }