Skip to content

Commit

Permalink
refactor: simplify setup of asset paths
Browse files Browse the repository at this point in the history
  • Loading branch information
cpvalente committed Oct 13, 2024
1 parent 78fa1df commit 2ff7019
Show file tree
Hide file tree
Showing 17 changed files with 178 additions and 145 deletions.
2 changes: 1 addition & 1 deletion apps/server/src/api-data/settings/settings.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@ import { getErrorMessage, obfuscate } from 'ontime-utils';

import type { Request, Response } from 'express';

import { isDocker } from '../../externals.js';
import { failEmptyObjects } from '../../utils/routerUtils.js';
import { isDocker } from '../../setup/index.js';
import { getDataProvider } from '../../classes/data-provider/DataProvider.js';

import { extractPin } from './settings.utils.js';
Expand Down
26 changes: 9 additions & 17 deletions apps/server/src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,8 @@ import serverTiming from 'server-timing';

// import utils
import { resolve } from 'path';
import {
srcDirectory,
environment,
isProduction,
resolveExternalsDirectory,
resolveStylesDirectory,
resolvedPath,
resolvePublicDirectoy,
} from './setup/index.js';
import { publicDir, srcDir } from './setup/index.js';
import { environment, isProduction } from './externals.js';
import { ONTIME_VERSION } from './ONTIME_VERSION.js';
import { consoleSuccess, consoleHighlight, consoleError } from './utils/console.js';

Expand Down Expand Up @@ -56,8 +49,8 @@ consoleHighlight(`Starting Ontime version ${ONTIME_VERSION}`);
const canLog = isProduction;
if (!canLog) {
console.log(`Ontime running in ${environment} environment`);
console.log(`Ontime source directory at ${srcDirectory} `);
console.log(`Ontime public directory at ${resolvePublicDirectoy} `);
console.log(`Ontime source directory at ${srcDir.root} `);
console.log(`Ontime public directory at ${publicDir.root} `);
}

// Create express APP
Expand All @@ -82,17 +75,16 @@ app.use(express.json({ limit: '1mb' }));
app.use('/data', appRouter); // router for application data
app.use('/api', integrationRouter); // router for integrations

// serve static - css
app.use('/external/styles', express.static(resolveStylesDirectory));
app.use('/external/', express.static(resolveExternalsDirectory));
// serve static external files
app.use('/external/', express.static(publicDir.externalDir));
// if the user reaches to the root, we show a 404
app.use('/external', (req, res) => {
res.status(404).send(`${req.originalUrl} not found`);
});

// serve static - react, in dev/test mode we fetch the React app from module
const reactAppPath = resolvedPath();
app.use(
expressStaticGzip(reactAppPath, {
expressStaticGzip(srcDir.clientDir, {
enableBrotli: true,
orderPreference: ['br'],
// when we build the client all the react subfiles will get a hashed name we can the immutable tag
Expand All @@ -103,7 +95,7 @@ app.use(
);

app.get('*', (_req, res) => {
res.sendFile(resolve(reactAppPath, 'index.html'));
res.sendFile(resolve(srcDir.clientDir, 'index.html'));
});

// Implement catch all
Expand Down
2 changes: 1 addition & 1 deletion apps/server/src/classes/Logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@ import { Log, LogLevel } from 'ontime-types';
import { generateId, millisToString } from 'ontime-utils';

import { clock } from '../services/Clock.js';
import { isProduction } from '../setup/index.js';
import { socket } from '../adapters/WebsocketAdapter.js';
import { consoleSubdued, consoleError } from '../utils/console.js';
import { isProduction } from '../externals.js';

class Logger {
private queue: Log[];
Expand Down
4 changes: 2 additions & 2 deletions apps/server/src/classes/data-provider/DataProvider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,11 @@ import {
import type { Low } from 'lowdb';
import { JSONFilePreset } from 'lowdb/node';

import { isTest } from '../../setup/index.js';
import { isPath } from '../../utils/fileManagement.js';
import { shouldCrashDev } from '../../utils/development.js';
import { isTest } from '../../externals.js';

import { safeMerge } from './DataProvider.utils.js';
import { shouldCrashDev } from '../../utils/development.js';

type ReadonlyPromise<T> = Promise<Readonly<T>>;

Expand Down
12 changes: 12 additions & 0 deletions apps/server/src/externals.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
/**
* This file contains a list of constants that may need to be resolved at runtime
*/

// =================================================
// resolve running environment
const env = process.env.NODE_ENV || 'production';

export const isTest = Boolean(process.env.IS_TEST);
export const environment = isTest ? 'test' : env;
export const isDocker = env === 'docker';
export const isProduction = isDocker || (env === 'production' && !isTest);
5 changes: 3 additions & 2 deletions apps/server/src/services/RestoreService.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import { MaybeNumber, MaybeString, Playback } from 'ontime-types';

import { JSONFile } from 'lowdb/node';
import { resolveRestoreFile } from '../setup/index.js';
import { deepEqual } from 'fast-equals';

import { publicFiles } from '../setup/index.js';

export type RestorePoint = {
playback: Playback;
selectedEventId: MaybeString;
Expand Down Expand Up @@ -147,4 +148,4 @@ export class RestoreService {
}
}

export const restoreService = new RestoreService(resolveRestoreFile);
export const restoreService = new RestoreService(publicFiles.restoreFile);
5 changes: 3 additions & 2 deletions apps/server/src/services/app-state-service/AppStateService.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
import { Low } from 'lowdb';
import { JSONFile } from 'lowdb/node';

import { appStatePath, isTest } from '../../setup/index.js';
import { publicFiles } from '../../setup/index.js';
import { isTest } from '../../externals.js';
import { isPath } from '../../utils/fileManagement.js';
import { shouldCrashDev } from '../../utils/development.js';

interface AppState {
lastLoadedProject?: string;
}

const adapter = new JSONFile<AppState>(appStatePath);
const adapter = new JSONFile<AppState>(publicFiles.appState);
const config = new Low<AppState>(adapter, {});

export async function isLastLoadedProject(projectName: string): Promise<boolean> {
Expand Down
15 changes: 7 additions & 8 deletions apps/server/src/services/project-service/ProjectService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { copyFile, rename } from 'fs/promises';

import { logger } from '../../classes/Logger.js';
import { getNetworkInterfaces } from '../../utils/networkInterfaces.js';
import { resolveCorruptDirectory, resolveProjectsDirectory, resolveStylesPath } from '../../setup/index.js';
import { publicDir } from '../../setup/index.js';
import {
appendToName,
ensureDirectory,
Expand Down Expand Up @@ -47,8 +47,8 @@ init();
* Ensure services has its dependencies initialized
*/
function init() {
ensureDirectory(resolveProjectsDirectory);
ensureDirectory(resolveCorruptDirectory);
ensureDirectory(publicDir.projectsDir);
ensureDirectory(publicDir.corruptDir);
}

export async function getCurrentProject() {
Expand All @@ -63,7 +63,7 @@ export async function getCurrentProject() {
* to be composed in the loading functions
*/
async function loadDemoProject(): Promise<string> {
const pathToNewFile = generateUniqueFileName(resolveProjectsDirectory, config.demoProject);
const pathToNewFile = generateUniqueFileName(publicDir.projectsDir, config.demoProject);
await initPersistence(getPathToProject(pathToNewFile), demoDb);
const newName = getFileNameFromPath(pathToNewFile);
await setLastLoadedProject(newName);
Expand All @@ -75,7 +75,7 @@ async function loadDemoProject(): Promise<string> {
* to be composed in the loading functions
*/
async function loadNewProject(): Promise<string> {
const pathToNewFile = generateUniqueFileName(resolveProjectsDirectory, config.newProject);
const pathToNewFile = generateUniqueFileName(publicDir.projectsDir, config.newProject);
await initPersistence(getPathToProject(pathToNewFile), dbModel);
const newName = getFileNameFromPath(pathToNewFile);
await setLastLoadedProject(newName);
Expand Down Expand Up @@ -273,7 +273,7 @@ export async function createProject(filename: string, projectData: ProjectData)
},
};

const uniqueFileName = generateUniqueFileName(resolveProjectsDirectory, filename);
const uniqueFileName = generateUniqueFileName(publicDir.projectsDir, filename);
const newFile = getPathToProject(uniqueFileName);

// change LowDB to point to new file
Expand Down Expand Up @@ -316,14 +316,13 @@ export async function getInfo(): Promise<GetInfo> {
// get nif and inject localhost
const ni = getNetworkInterfaces();
ni.unshift({ name: 'localhost', address: '127.0.0.1' });
const cssOverride = resolveStylesPath;

return {
networkInterfaces: ni,
version,
serverPort,
osc,
cssOverride,
cssOverride: publicDir.stylesDir,
};
}

Expand Down
14 changes: 7 additions & 7 deletions apps/server/src/services/project-service/projectServiceUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { existsSync } from 'fs';
import { copyFile, readFile, rename, stat } from 'fs/promises';
import { extname, join } from 'path';

import { resolveCorruptDirectory, resolveProjectsDirectory } from '../../setup/index.js';
import { publicDir } from '../../setup/index.js';
import { getFilesFromFolder, removeFileExtension } from '../../utils/fileManagement.js';

/**
Expand All @@ -13,7 +13,7 @@ import { getFilesFromFolder, removeFileExtension } from '../../utils/fileManagem
* @param name
*/
export async function handleUploaded(filePath: string, name: string) {
const newFilePath = join(resolveProjectsDirectory, name);
const newFilePath = join(publicDir.projectsDir, name);
await rename(filePath, newFilePath);
}

Expand All @@ -29,12 +29,12 @@ export async function handleUploaded(filePath: string, name: string) {
* @throws {Error} Throws an error if there is an issue in reading the directory or fetching file statistics.
*/
export async function getProjectFiles(): Promise<ProjectFile[]> {
const allFiles = await getFilesFromFolder(resolveProjectsDirectory);
const allFiles = await getFilesFromFolder(publicDir.projectsDir);
const filteredFiles = filterProjectFiles(allFiles);

const projectFiles: ProjectFile[] = [];
for (const file of filteredFiles) {
const filePath = join(resolveProjectsDirectory, file);
const filePath = join(publicDir.projectsDir, file);
const stats = await stat(filePath);

projectFiles.push({
Expand Down Expand Up @@ -62,22 +62,22 @@ export function doesProjectExist(name: string): MaybeString {
* Returns the absolute path to a project file
*/
export function getPathToProject(name: string): string {
return join(resolveProjectsDirectory, name);
return join(publicDir.projectsDir, name);
}

/**
* Makes a copy of a given project to the corrupted directory
*/
export async function copyCorruptFile(filePath: string, name: string): Promise<void> {
const newPath = join(resolveCorruptDirectory, name);
const newPath = join(publicDir.corruptDir, name);
return copyFile(filePath, newPath);
}

/**
* Moves a file permanently to the corrupted directory
*/
export async function moveCorruptFile(filePath: string, name: string): Promise<void> {
const newPath = join(resolveCorruptDirectory, name);
const newPath = join(publicDir.corruptDir, name);
return rename(filePath, newPath);
}

Expand Down
4 changes: 2 additions & 2 deletions apps/server/src/services/sheet-service/SheetService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import { sheets, sheets_v4 } from '@googleapis/sheets';
import { Credentials, OAuth2Client } from 'google-auth-library';
import got from 'got';

import { resolveSheetsDirectory } from '../../setup/index.js';
import { publicDir } from '../../setup/index.js';
import { ensureDirectory } from '../../utils/fileManagement.js';
import { cellRequestFromEvent, type ClientSecret, getA1Notation, validateClientSecret } from './sheetUtils.js';
import { parseExcel } from '../../utils/parser.js';
Expand Down Expand Up @@ -57,7 +57,7 @@ function reset() {
*/
export function init() {
reset();
ensureDirectory(resolveSheetsDirectory);
ensureDirectory(publicDir.sheetsDir);
}

/**
Expand Down
Loading

0 comments on commit 2ff7019

Please sign in to comment.