Setup eslint and enforce rules
All checks were successful
continuous-integration/drone/push Build is passing

This commit is contained in:
2021-06-02 22:36:25 -05:00
parent 82e7a1f299
commit 1d5056b753
149 changed files with 6104 additions and 3114 deletions

View File

@@ -1,5 +1,5 @@
import {Application} from './Application';
import {Container, DependencyKey} from "../di";
import {Application} from './Application'
import {Container, DependencyKey} from '../di'
/**
* Base type for a class that supports binding methods by string.
@@ -13,12 +13,12 @@ export interface Bindable {
* @param what
* @return boolean
*/
export function isBindable(what: any): what is Bindable {
export function isBindable(what: unknown): what is Bindable {
return (
what
&& typeof what.getBoundMethod === 'function'
&& what.getBoundMethod.length === 1
&& typeof what.getBoundMethod('getBoundMethod') === 'function'
Boolean(what)
&& typeof (what as any).getBoundMethod === 'function'
&& (what as any).getBoundMethod.length === 1
&& typeof (what as any).getBoundMethod('getBoundMethod') === 'function'
)
}
@@ -30,17 +30,17 @@ export class AppClass {
private readonly appClassApplication!: Application;
constructor() {
this.appClassApplication = Application.getApplication();
this.appClassApplication = Application.getApplication()
}
/** Get the global Application. */
protected app(): Application {
return this.appClassApplication;
return this.appClassApplication
}
/** Get the global Container. */
protected container(): Container {
return this.appClassApplication;
return this.appClassApplication
}
/** Call the `make()` method on the global container. */
@@ -54,14 +54,12 @@ export class AppClass {
* @return function
*/
public getBoundMethod(methodName: string): (...args: any[]) => any {
// @ts-ignore
if ( typeof this[methodName] !== 'function' ) {
if ( typeof (this as any)[methodName] !== 'function' ) {
throw new TypeError(`Attempt to get bound method for non-function type: ${methodName}`)
}
return (...args: any[]): any => {
// @ts-ignore
return this[methodName](...args)
return (this as any)[methodName](...args)
}
}
}

View File

@@ -1,4 +1,4 @@
import {Container} from '../di';
import {Container} from '../di'
import {
ErrorWithContext,
globalRegistry,
@@ -7,14 +7,14 @@ import {
PathLike,
StandardLogger,
universalPath,
UniversalPath
} from '../util';
UniversalPath,
} from '../util'
import {Logging} from '../service/Logging';
import {RunLevelErrorHandler} from "./RunLevelErrorHandler";
import {Unit, UnitStatus} from "./Unit";
import * as dotenv from 'dotenv';
import {CacheFactory} from "../support/cache/CacheFactory";
import {Logging} from '../service/Logging'
import {RunLevelErrorHandler} from './RunLevelErrorHandler'
import {Unit, UnitStatus} from './Unit'
import * as dotenv from 'dotenv'
import {CacheFactory} from '../support/cache/CacheFactory'
/**
* Helper function that resolves and infers environment variable values.
@@ -24,7 +24,7 @@ import {CacheFactory} from "../support/cache/CacheFactory";
* @param key
* @param defaultValue
*/
export function env(key: string, defaultValue?: any): any {
export function env(key: string, defaultValue?: unknown): any {
return Application.getApplication().env(key, defaultValue)
}
@@ -107,7 +107,7 @@ export class Application extends Container {
* If true, the "Starting Extollo..." messages will always
* be logged.
*/
public forceStartupMessage: boolean = true
public forceStartupMessage = true
constructor() {
super()
@@ -129,21 +129,21 @@ export class Application extends Container {
* Returns true if the given unit class is registered with the application.
* @param unitClass
*/
public hasUnit(unitClass: typeof Unit) {
public hasUnit(unitClass: typeof Unit): boolean {
return this.applicationUnits.includes(unitClass)
}
/**
* Return a UniversalPath to the root of the application.
*/
get root() {
get root(): UniversalPath {
return this.basePath.concat()
}
/**
* Returns a UniversalPath to the `app/` directory in the application.
*/
get appRoot() {
get appRoot(): UniversalPath {
return this.basePath.concat('app')
}
@@ -151,7 +151,7 @@ export class Application extends Container {
* Resolve a path relative to the root of the application.
* @param parts
*/
path(...parts: PathLike[]) {
path(...parts: PathLike[]): UniversalPath {
return this.basePath.concat(...parts)
}
@@ -159,14 +159,14 @@ export class Application extends Container {
* Resolve a path relative to the `app/` directory in the application.
* @param parts
*/
appPath(...parts: PathLike[]) {
appPath(...parts: PathLike[]): UniversalPath {
return this.basePath.concat('app', ...parts)
}
/**
* Get an instance of the RunLevelErrorHandler.
*/
get errorHandler() {
get errorHandler(): (e: Error) => void {
const rleh: RunLevelErrorHandler = this.make<RunLevelErrorHandler>(RunLevelErrorHandler)
return rleh.handle
}
@@ -186,7 +186,7 @@ export class Application extends Container {
* @param absolutePathToApplicationRoot
* @param applicationUnits
*/
scaffold(absolutePathToApplicationRoot: string, applicationUnits: (typeof Unit)[]) {
scaffold(absolutePathToApplicationRoot: string, applicationUnits: (typeof Unit)[]): void {
this.baseDir = absolutePathToApplicationRoot
this.basePath = universalPath(absolutePathToApplicationRoot)
this.applicationUnits = applicationUnits
@@ -203,32 +203,30 @@ export class Application extends Container {
* Initialize the logger and load the logging level from the environment.
* @protected
*/
protected setupLogging() {
protected setupLogging(): void {
const standard: StandardLogger = this.make<StandardLogger>(StandardLogger)
const logging: Logging = this.make<Logging>(Logging)
logging.registerLogger(standard)
logging.verbose('Attempting to load logging level from the environment...')
try {
logging.verbose('Attempting to load logging level from the environment...')
const envLevel = this.env('EXTOLLO_LOGGING_LEVEL')
logging.verbose(`Read logging level: ${envLevel}`)
const envLevel = this.env('EXTOLLO_LOGGING_LEVEL')
logging.verbose(`Read logging level: ${envLevel}`)
if ( isLoggingLevel(envLevel) ) {
logging.verbose('Logging level is valid.')
logging.level = envLevel
logging.debug(`Set logging level from environment: ${envLevel}`)
}
} catch(e) {}
if ( isLoggingLevel(envLevel) ) {
logging.verbose('Logging level is valid.')
logging.level = envLevel
logging.debug(`Set logging level from environment: ${envLevel}`)
}
}
/**
* Initialize the environment variable library and read from the `.env` file.
* @protected
*/
protected bootstrapEnvironment() {
protected bootstrapEnvironment(): void {
dotenv.config({
path: this.basePath.concat('.env').toLocal
path: this.basePath.concat('.env').toLocal,
})
}
@@ -238,14 +236,14 @@ export class Application extends Container {
* @param key
* @param defaultValue
*/
public env(key: string, defaultValue?: any): any {
public env(key: string, defaultValue?: unknown): any {
return infer(process.env[key] ?? '') ?? defaultValue
}
/**
* Run the application by starting all units in order, then stopping them in reverse order.
*/
async run() {
async run(): Promise<void> {
try {
await this.up()
await this.down()
@@ -257,7 +255,7 @@ export class Application extends Container {
/**
* Start all units in the application, one at a time, in order.
*/
async up() {
async up(): Promise<void> {
const logging: Logging = this.make<Logging>(Logging)
logging.info('Starting Extollo...', this.forceStartupMessage)
@@ -271,12 +269,14 @@ export class Application extends Container {
/**
* Stop all units in the application, one at a time, in reverse order.
*/
async down() {
async down(): Promise<void> {
const logging: Logging = this.make<Logging>(Logging)
logging.info('Stopping Extollo...', this.forceStartupMessage)
for ( const unit of [...this.instantiatedUnits].reverse() ) {
if ( !unit ) continue
if ( !unit ) {
continue
}
await this.stopUnit(unit)
}
}
@@ -285,7 +285,7 @@ export class Application extends Container {
* Start a single unit, setting its status.
* @param unit
*/
public async startUnit(unit: Unit) {
public async startUnit(unit: Unit): Promise<void> {
const logging: Logging = this.make<Logging>(Logging)
try {
@@ -296,8 +296,7 @@ export class Application extends Container {
logging.info(`Started ${unit.constructor.name}.`)
} catch (e) {
unit.status = UnitStatus.Error
console.log(e)
throw this.errorWrapContext(e, {unit_name: unit.constructor.name})
throw this.errorWrapContext(e, {unitName: unit.constructor.name})
}
}
@@ -305,7 +304,7 @@ export class Application extends Container {
* Stop a single unit, setting its status.
* @param unit
*/
public async stopUnit(unit: Unit) {
public async stopUnit(unit: Unit): Promise<void> {
const logging: Logging = this.make<Logging>(Logging)
try {
@@ -316,7 +315,7 @@ export class Application extends Container {
logging.info(`Stopped ${unit.constructor.name}.`)
} catch (e) {
unit.status = UnitStatus.Error
throw this.errorWrapContext(e, {unit_name: unit.constructor.name})
throw this.errorWrapContext(e, {unitName: unit.constructor.name})
}
}
}

View File

@@ -1,7 +1,7 @@
import * as color from 'colors/safe'
import {Logging} from "../service/Logging";
import {Inject} from "../di";
import {ErrorWithContext} from "../util";
import {Logging} from '../service/Logging'
import {Inject} from '../di'
import {ErrorWithContext} from '../util'
/**
* Class with logic for handling errors that are thrown at the run-level of the application.
@@ -30,7 +30,8 @@ export class RunLevelErrorHandler {
*/
wrapContext(e: Error, context: {[key: string]: any}): ErrorWithContext {
if ( e instanceof ErrorWithContext ) {
e.context = {...e.context, ...context}
e.context = {...e.context,
...context}
return e
}
@@ -45,15 +46,18 @@ export class RunLevelErrorHandler {
* Log the error to the logger.
* @param {Error} e
*/
display(e: Error) {
display(e: Error): void {
let operativeError = e
let context: {[key: string]: string} = {}
if ( e instanceof ErrorWithContext ) {
if ( e.originalError ) operativeError = e.originalError
if ( e.originalError ) {
operativeError = e.originalError
}
context = e.context
}
const contextDisplay = Object.keys(context).map(key => ` - ${key}: ${context[key]}`).join('\n')
const contextDisplay = Object.keys(context).map(key => ` - ${key}: ${context[key]}`)
.join('\n')
try {
let errorString = `RunLevelErrorHandler invoked:
@@ -73,12 +77,12 @@ With the following context:
${contextDisplay}
`
}
this.logging.error(errorString, true)
} catch (display_e) {
} catch (displayError) {
// The error display encountered an error...
// just throw the original so it makes it out
console.error('RunLevelErrorHandler encountered an error:', display_e.message)
console.error('RunLevelErrorHandler encountered an error:', displayError.message) // eslint-disable-line no-console
throw operativeError
}
}

View File

@@ -1,4 +1,4 @@
import {AppClass} from './AppClass';
import {AppClass} from './AppClass'
/**
* The various statuses of a Unit.
@@ -23,7 +23,7 @@ export abstract class Unit extends AppClass {
* This method is called to start the unit when the application is booting.
* Here, you should do any setup required to get the package up and running.
*/
public up(): Promise<void> | void {}
public up(): Promise<void> | void {} // eslint-disable-line @typescript-eslint/no-empty-function
/**
* This method is called to stop the unit when the application is shutting down.
@@ -32,5 +32,5 @@ export abstract class Unit extends AppClass {
* IN PARTICULAR take care to free blocking resources that could prevent the
* process from exiting without a kill.
*/
public down(): Promise<void> | void {}
public down(): Promise<void> | void {} // eslint-disable-line @typescript-eslint/no-empty-function
}