Skip to content

Commit

Permalink
refactoring
Browse files Browse the repository at this point in the history
- separate app start from task start, allows for multiple app workers
- rename helper files
  • Loading branch information
dangowans committed Jan 2, 2025
1 parent 6a39891 commit 63c2c6e
Show file tree
Hide file tree
Showing 86 changed files with 683 additions and 427 deletions.
1 change: 1 addition & 0 deletions app/app.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export declare const app: import("express-serve-static-core").Express;
55 changes: 12 additions & 43 deletions app.js → app/app.js
Original file line number Diff line number Diff line change
@@ -1,30 +1,26 @@
import http from 'node:http';
import path from 'node:path';
import FasterUrlBuilder from '@cityssm/faster-url-builder';
import { secondsToMillis } from '@cityssm/to-millis';
import cookieParser from 'cookie-parser';
import Debug from 'debug';
import { asyncExitHook } from 'exit-hook';
import express from 'express';
import session from 'express-session';
import createError from 'http-errors';
import schedule from 'node-schedule';
import FileStore from 'session-file-store';
import { initializeUserDatabase } from './database/helpers.userDatabase.js';
import { sessionCheckHandler } from './handlers/session.js';
import * as configFunctions from './helpers/functions.config.js';
import router_dashboard from './routers/dashboard.js';
import router_login from './routers/login.js';
import { version } from './version.js';
const debug = Debug('faster-web-helper:app');
import { initializeUserDatabase } from '../database/helpers.userDatabase.js';
import { sessionCheckHandler } from '../handlers/session.js';
import * as configFunctions from '../helpers/config.functions.js';
import router_dashboard from '../routers/dashboard.js';
import router_login from '../routers/login.js';
import { version } from '../version.js';
const debug = Debug(`faster-web-helper:app:${process.pid}`);
/*
* Initialize databases
*/
initializeUserDatabase();
/*
* Initialize app
*/
const app = express();
export const app = express();
app.set('views', path.join('views'));
app.set('view engine', 'ejs');
app.use((request, _response, next) => {
Expand Down Expand Up @@ -108,27 +104,14 @@ app.get(`${urlPrefix}/logout`, (request, response) => {
/*
* Initialize modules
*/
const options = {
app
};
const promises = [];
if (configFunctions.getConfigProperty('modules.autocomplete.isEnabled')) {
const initializeAutocompleteModule = await import('./modules/autocomplete/initializeAutocompleteModule.js');
promises.push(initializeAutocompleteModule.default(options));
const initializeAutocompleteModule = await import('../modules/autocomplete/initializeAutocompleteModule.js');
initializeAutocompleteModule.initializeAutocompleteAppHandlers(app);
}
if (configFunctions.getConfigProperty('modules.inventoryScanner.isEnabled')) {
const initializeInventoryScannerModule = await import('./modules/inventoryScanner/initialize.js');
initializeInventoryScannerModule.default(options);
const initializeInventoryScannerModule = await import('../modules/inventoryScanner/initializeInventoryScanner.js');
initializeInventoryScannerModule.initializeInventoryScannerAppHandlers(app);
}
if (configFunctions.getConfigProperty('modules.worktechUpdate.isEnabled')) {
const initializeWorktechUpdateModule = await import('./modules/worktechUpdate/initialize.js');
initializeWorktechUpdateModule.default(options);
}
if (configFunctions.getConfigProperty('modules.tempFolderCleanup.isEnabled')) {
const initializeTempFolderCleanupModule = await import('./modules/tempFolderCleanup/initializeTempFolderCleanupModule.js');
initializeTempFolderCleanupModule.default(options);
}
await Promise.all(promises);
/*
* Error handling
*/
Expand All @@ -146,17 +129,3 @@ app.use((error, request, response) => {
response.status(error.status || 500);
response.render('error');
});
/*
* Initialize server
*/
const httpPort = configFunctions.getConfigProperty('webServer.httpPort');
// eslint-disable-next-line @typescript-eslint/no-misused-promises
const httpServer = http.createServer(app);
httpServer.listen(httpPort);
debug(`HTTP listening on ${httpPort.toString()}`);
asyncExitHook(async () => {
await schedule.gracefulShutdown();
httpServer.close();
}, {
wait: secondsToMillis(1)
});
73 changes: 12 additions & 61 deletions app.ts → app/app.ts
Original file line number Diff line number Diff line change
@@ -1,26 +1,21 @@
import http from 'node:http'
import path from 'node:path'

import FasterUrlBuilder from '@cityssm/faster-url-builder'
import { secondsToMillis } from '@cityssm/to-millis'
import cookieParser from 'cookie-parser'
import Debug from 'debug'
import { asyncExitHook } from 'exit-hook'
import express from 'express'
import session from 'express-session'
import createError from 'http-errors'
import schedule from 'node-schedule'
import FileStore from 'session-file-store'

import { initializeUserDatabase } from './database/helpers.userDatabase.js'
import { sessionCheckHandler } from './handlers/session.js'
import * as configFunctions from './helpers/functions.config.js'
import type { ModuleInitializerOptions } from './modules/types.js'
import router_dashboard from './routers/dashboard.js'
import router_login from './routers/login.js'
import { version } from './version.js'
import { initializeUserDatabase } from '../database/helpers.userDatabase.js'
import { sessionCheckHandler } from '../handlers/session.js'
import * as configFunctions from '../helpers/config.functions.js'
import router_dashboard from '../routers/dashboard.js'
import router_login from '../routers/login.js'
import { version } from '../version.js'

const debug = Debug('faster-web-helper:app')
const debug = Debug(`faster-web-helper:app:${process.pid}`)

/*
* Initialize databases
Expand All @@ -32,7 +27,7 @@ initializeUserDatabase()
* Initialize app
*/

const app = express()
export const app = express()

app.set('views', path.join('views'))
app.set('view engine', 'ejs')
Expand Down Expand Up @@ -177,42 +172,20 @@ app.get(`${urlPrefix}/logout`, (request, response) => {
* Initialize modules
*/

const options: ModuleInitializerOptions = {
app
}

const promises: Array<Promise<void>> = []

if (configFunctions.getConfigProperty('modules.autocomplete.isEnabled')) {
const initializeAutocompleteModule = await import(
'./modules/autocomplete/initializeAutocompleteModule.js'
'../modules/autocomplete/initializeAutocompleteModule.js'
)
promises.push(initializeAutocompleteModule.default(options))
initializeAutocompleteModule.initializeAutocompleteAppHandlers(app)
}

if (configFunctions.getConfigProperty('modules.inventoryScanner.isEnabled')) {
const initializeInventoryScannerModule = await import(
'./modules/inventoryScanner/initialize.js'
)
initializeInventoryScannerModule.default(options)
}

if (configFunctions.getConfigProperty('modules.worktechUpdate.isEnabled')) {
const initializeWorktechUpdateModule = await import(
'./modules/worktechUpdate/initialize.js'
'../modules/inventoryScanner/initializeInventoryScanner.js'
)
initializeWorktechUpdateModule.default(options)
initializeInventoryScannerModule.initializeInventoryScannerAppHandlers(app)
}

if (configFunctions.getConfigProperty('modules.tempFolderCleanup.isEnabled')) {
const initializeTempFolderCleanupModule = await import(
'./modules/tempFolderCleanup/initializeTempFolderCleanupModule.js'
)
initializeTempFolderCleanupModule.default(options)
}

await Promise.all(promises)

/*
* Error handling
*/
Expand All @@ -239,25 +212,3 @@ app.use(
response.render('error')
}
)

/*
* Initialize server
*/

const httpPort = configFunctions.getConfigProperty('webServer.httpPort')

// eslint-disable-next-line @typescript-eslint/no-misused-promises
const httpServer = http.createServer(app)

httpServer.listen(httpPort)
debug(`HTTP listening on ${httpPort.toString()}`)

asyncExitHook(
async () => {
await schedule.gracefulShutdown()
httpServer.close()
},
{
wait: secondsToMillis(1)
}
)
File renamed without changes.
54 changes: 54 additions & 0 deletions app/appProcess.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
// eslint-disable-next-line @eslint-community/eslint-comments/disable-enable-pair
/* eslint-disable unicorn/no-process-exit */
import http from 'node:http';
import Debug from 'debug';
import exitHook from 'exit-hook';
import { getConfigProperty } from '../helpers/config.functions.js';
import { app } from './app.js';
const debug = Debug(`faster-web-helper:appProcess:${process.pid}`);
function onError(error) {
if (error.syscall !== 'listen') {
throw error;
}
// handle specific listen errors with friendly messages
switch (error.code) {
case 'EACCES': {
debug('Requires elevated privileges');
process.exit(1);
// break;
}
// eslint-disable-next-line no-fallthrough
case 'EADDRINUSE': {
debug('Port is already in use.');
process.exit(1);
// break;
}
// eslint-disable-next-line no-fallthrough
default: {
throw error;
}
}
}
function onListening(server) {
const addr = server.address();
if (addr !== null) {
const bind = typeof addr === 'string' ? `pipe ${addr}` : `port ${addr.port.toString()}`;
debug(`HTTP Listening on ${bind}`);
}
}
/*
* Initialize HTTP
*/
process.title = `Faster Web Helper (Worker)`;
const httpPort = getConfigProperty('webServer.httpPort');
// eslint-disable-next-line @typescript-eslint/no-misused-promises
const httpServer = http.createServer(app);
httpServer.listen(httpPort);
httpServer.on('error', onError);
httpServer.on('listening', () => {
onListening(httpServer);
});
exitHook(() => {
debug('Closing HTTP');
httpServer.close();
});
78 changes: 78 additions & 0 deletions app/appProcess.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
// eslint-disable-next-line @eslint-community/eslint-comments/disable-enable-pair
/* eslint-disable unicorn/no-process-exit */

import http from 'node:http'

import Debug from 'debug'
import exitHook from 'exit-hook'

import { getConfigProperty } from '../helpers/config.functions.js'

import { app } from './app.js'

const debug = Debug(`faster-web-helper:appProcess:${process.pid}`)

interface ServerError extends Error {
syscall: string
code: string
}

function onError(error: ServerError): void {
if (error.syscall !== 'listen') {
throw error
}

// handle specific listen errors with friendly messages
switch (error.code) {
case 'EACCES': {
debug('Requires elevated privileges')
process.exit(1)
// break;
}

// eslint-disable-next-line no-fallthrough
case 'EADDRINUSE': {
debug('Port is already in use.')
process.exit(1)
// break;
}

// eslint-disable-next-line no-fallthrough
default: {
throw error
}
}
}

function onListening(server: http.Server): void {
const addr = server.address()

if (addr !== null) {
const bind =
typeof addr === 'string' ? `pipe ${addr}` : `port ${addr.port.toString()}`
debug(`HTTP Listening on ${bind}`)
}
}

/*
* Initialize HTTP
*/

process.title = `Faster Web Helper (Worker)`

const httpPort = getConfigProperty('webServer.httpPort')

// eslint-disable-next-line @typescript-eslint/no-misused-promises
const httpServer = http.createServer(app)

httpServer.listen(httpPort)

httpServer.on('error', onError)
httpServer.on('listening', () => {
onListening(httpServer)
})

exitHook(() => {
debug('Closing HTTP')
httpServer.close()
})
2 changes: 1 addition & 1 deletion database/createUser.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import sqlite from 'better-sqlite3';
import { generateKeyGuid } from '../helpers/functions.user.js';
import { generateKeyGuid } from '../helpers/users.functions.js';
import { databasePath } from './helpers.userDatabase.js';
export default function createUser(user) {
const rightNow = Date.now();
Expand Down
2 changes: 1 addition & 1 deletion database/createUser.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import sqlite from 'better-sqlite3'

import { generateKeyGuid } from '../helpers/functions.user.js'
import { generateKeyGuid } from '../helpers/users.functions.js'

import { databasePath } from './helpers.userDatabase.js'

Expand Down
3 changes: 2 additions & 1 deletion eslint.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,8 @@ export const config = tseslint.config(...configWebApp, {
'@typescript-eslint/no-unsafe-assignment': 'off',
'@typescript-eslint/no-unsafe-argument': 'off',
'@typescript-eslint/no-unsafe-call': 'off',
'@typescript-eslint/no-unsafe-member-access': 'off'
'@typescript-eslint/no-unsafe-member-access': 'off',
'@typescript-eslint/no-unsafe-type-assertion': 'off'
}
});
export default config;
Loading

0 comments on commit 63c2c6e

Please sign in to comment.