BaseFileWatcher.ts
1 import chokidar from 'chokidar' 2 import pkgDir from 'pkg-dir' 3 import { SQLiteDataEngine } from '../../datapack/engine/sqlite' 4 import logSymbols from 'log-symbols' 5 import path from 'path' 6 7 const rootDirectory = pkgDir.sync( __dirname ) 8 9 class SQLiteHtmlEngine extends SQLiteDataEngine { 10 protected getAdjustedPath( filePath: string ): string { 11 let gameServerPath = rootDirectory.replace( 'cli', 'game-server' ) 12 return `${gameServerPath}/${filePath}` 13 } 14 } 15 16 export abstract class BaseFileWatcher { 17 engine: SQLiteHtmlEngine 18 19 constructor( path: string ) { 20 console.log( logSymbols.info, 'File Watcher:', this.getName() ) 21 this.initialize( path ) 22 } 23 24 async initialize( filePath: string ) : Promise<void> { 25 this.engine = new SQLiteHtmlEngine() 26 27 let directory = path.normalize( `${rootDirectory}/${filePath}` ) 28 chokidar.watch( directory, { 29 ignoreInitial: true, 30 persistent: true 31 } ) 32 .on( 'add', this.onAdd.bind( this ) ) 33 .on( 'change', this.onChange.bind( this ) ) 34 .on( 'unlink', this.onRemove.bind( this ) ) 35 .on( 'ready', this.onReady.bind( this ) ) 36 37 /* 38 Used by various restart utilities that manage application process. 39 */ 40 process.once( 'SIGUSR1', this.shutdownSequence.bind( this ) ) 41 process.once( 'SIGUSR2', this.shutdownSequence.bind( this ) ) 42 43 /* 44 Used by terminal applications to interrupt process, aka Ctrl + C. 45 */ 46 process.on( 'SIGINT', this.shutdownSequence.bind( this ) ) 47 48 /* 49 Termination signal used by OS to signify process must be killed (similar to SIGKILL). 50 */ 51 process.on( 'SIGTERM', this.shutdownSequence.bind( this ) ) 52 console.log( logSymbols.success, 'Monitoring directory:', directory ) 53 } 54 55 abstract onAdd( filePath: string ) : Promise<void> 56 abstract onChange( filePath: string ) : Promise<void> 57 abstract onRemove( filePath: string ) : Promise<void> 58 protected onReady() : Promise<void> { 59 console.log( logSymbols.success, 'Listening for events...' ) 60 return this.engine.start( this.getDatabasePath() ) 61 } 62 63 async shutdownSequence() : Promise<void> { 64 await this.engine.finish() 65 console.log( logSymbols.info, 'Shutdown complete' ) 66 67 process.exit() 68 } 69 70 protected getDatabasePath() : string { 71 return 'datapack.database' 72 } 73 74 abstract getName() : string 75 }