Browse Source

refactor: Prefix protected attributes with _

Owen Diffey 1 year ago
parent
commit
527acab5a3

+ 6 - 0
backend/.eslintrc

@@ -53,6 +53,12 @@
 				"modifiers": ["private"],
 				"format": null,
 				"leadingUnderscore": "require"
+			},
+			{
+				"selector": "memberLike",
+				"modifiers": ["protected"],
+				"format": null,
+				"leadingUnderscore": "require"
 			}
 		],
 		"no-void": 0,

+ 42 - 42
backend/src/BaseModule.ts

@@ -15,21 +15,21 @@ export enum ModuleStatus {
 }
 
 export default abstract class BaseModule {
-	protected moduleManager: ModuleManager;
+	protected _moduleManager: ModuleManager;
 
-	protected logBook: LogBook;
+	protected _logBook: LogBook;
 
-	protected jobQueue: JobQueue;
+	protected _jobQueue: JobQueue;
 
-	protected name: string;
+	protected _name: string;
 
-	protected status: ModuleStatus;
+	protected _status: ModuleStatus;
 
-	protected dependentModules: (keyof Modules)[];
+	protected _dependentModules: (keyof Modules)[];
 
-	protected jobApiDefault: boolean;
+	protected _jobApiDefault: boolean;
 
-	protected jobConfig: Record<
+	protected _jobConfig: Record<
 		string,
 		| boolean
 		| {
@@ -38,7 +38,7 @@ export default abstract class BaseModule {
 		  }
 	>;
 
-	protected jobs: Record<
+	protected _jobs: Record<
 		string,
 		{
 			api: boolean;
@@ -52,16 +52,16 @@ export default abstract class BaseModule {
 	 * @param name - Module name
 	 */
 	public constructor(name: string) {
-		this.moduleManager = ModuleManager.getPrimaryInstance();
-		this.logBook = LogBook.getPrimaryInstance();
-		this.jobQueue = JobQueue.getPrimaryInstance();
-		this.name = name;
-		this.status = ModuleStatus.LOADED;
-		this.dependentModules = [];
-		this.jobApiDefault = true;
-		this.jobConfig = {};
-		this.jobs = {};
-		this.log(`Module (${this.name}) loaded`);
+		this._moduleManager = ModuleManager.getPrimaryInstance();
+		this._logBook = LogBook.getPrimaryInstance();
+		this._jobQueue = JobQueue.getPrimaryInstance();
+		this._name = name;
+		this._status = ModuleStatus.LOADED;
+		this._dependentModules = [];
+		this._jobApiDefault = true;
+		this._jobConfig = {};
+		this._jobs = {};
+		this.log(`Module (${this._name}) loaded`);
 	}
 
 	/**
@@ -70,7 +70,7 @@ export default abstract class BaseModule {
 	 * @returns name
 	 */
 	public getName() {
-		return this.name;
+		return this._name;
 	}
 
 	/**
@@ -79,7 +79,7 @@ export default abstract class BaseModule {
 	 * @returns status
 	 */
 	public getStatus() {
-		return this.status;
+		return this._status;
 	}
 
 	/**
@@ -88,21 +88,21 @@ export default abstract class BaseModule {
 	 * @param status - Module status
 	 */
 	public setStatus(status: ModuleStatus) {
-		this.status = status;
+		this._status = status;
 	}
 
 	/**
 	 * getDependentModules - Get module dependencies
 	 */
 	public getDependentModules() {
-		return this.dependentModules;
+		return this._dependentModules;
 	}
 
 	/**
 	 * _loadJobs - Load jobs available via api module
 	 */
 	private async _loadJobs() {
-		this.jobs = {};
+		this._jobs = {};
 
 		const module = Object.getPrototypeOf(this);
 		await Promise.all(
@@ -116,9 +116,9 @@ export default abstract class BaseModule {
 				)
 					return;
 
-				const options = this.jobConfig[property];
+				const options = this._jobConfig[property];
 
-				let api = this.jobApiDefault;
+				let api = this._jobApiDefault;
 				if (
 					typeof options === "object" &&
 					typeof options.api === "boolean"
@@ -126,7 +126,7 @@ export default abstract class BaseModule {
 					api = options.api;
 				else if (typeof options === "boolean") api = options;
 
-				this.jobs[property] = {
+				this._jobs[property] = {
 					api,
 					method: module[property]
 				};
@@ -134,16 +134,16 @@ export default abstract class BaseModule {
 		);
 
 		await Promise.all(
-			Object.entries(this.jobConfig).map(async ([name, options]) => {
+			Object.entries(this._jobConfig).map(async ([name, options]) => {
 				if (
 					typeof options === "object" &&
 					typeof options.method === "function"
 				) {
-					if (this.jobs[name])
+					if (this._jobs[name])
 						throw new Error(`Job "${name}" is already defined`);
 
-					this.jobs[name] = {
-						api: options.api ?? this.jobApiDefault,
+					this._jobs[name] = {
+						api: options.api ?? this._jobApiDefault,
 						method: options.method
 					};
 				}
@@ -155,25 +155,25 @@ export default abstract class BaseModule {
 	 * getJob - Get module job
 	 */
 	public getJob(name: string) {
-		if (!this.jobs[name]) throw new Error(`Job "${name}" not found.`);
+		if (!this._jobs[name]) throw new Error(`Job "${name}" not found.`);
 
-		return this.jobs[name];
+		return this._jobs[name];
 	}
 
 	/**
 	 * startup - Startup module
 	 */
 	public async startup() {
-		this.log(`Module (${this.name}) starting`);
+		this.log(`Module (${this._name}) starting`);
 		this.setStatus(ModuleStatus.STARTING);
 	}
 
 	/**
 	 * started - called with the module has started
 	 */
-	protected async started() {
+	protected async _started() {
 		await this._loadJobs();
-		this.log(`Module (${this.name}) started`);
+		this.log(`Module (${this._name}) started`);
 		this.setStatus(ModuleStatus.STARTED);
 	}
 
@@ -181,15 +181,15 @@ export default abstract class BaseModule {
 	 * shutdown - Shutdown module
 	 */
 	public async shutdown() {
-		this.log(`Module (${this.name}) stopping`);
+		this.log(`Module (${this._name}) stopping`);
 		this.setStatus(ModuleStatus.STOPPING);
 	}
 
 	/**
 	 * stopped - called when the module has stopped
 	 */
-	protected async stopped() {
-		this.log(`Module (${this.name}) stopped`);
+	protected async _stopped() {
+		this.log(`Module (${this._name}) stopped`);
 		this.setStatus(ModuleStatus.STOPPED);
 	}
 
@@ -198,7 +198,7 @@ export default abstract class BaseModule {
 	 *
 	 * @param log - Log message or object
 	 */
-	protected log(log: string | Omit<Log, "timestamp" | "category">) {
+	public log(log: string | Omit<Log, "timestamp" | "category">) {
 		const {
 			message,
 			type = undefined,
@@ -206,12 +206,12 @@ export default abstract class BaseModule {
 		} = {
 			...(typeof log === "string" ? { message: log } : log)
 		};
-		this.logBook.log({
+		this._logBook.log({
 			message,
 			type,
 			category: `modules.${this.getName()}`,
 			data: {
-				moduleName: this.name,
+				moduleName: this._name,
 				...data
 			}
 		});

+ 53 - 53
backend/src/Job.ts

@@ -14,19 +14,19 @@ export enum JobStatus {
 }
 
 export default class Job {
-	protected name: string;
+	private _name: string;
 
-	protected module: Modules[keyof Modules];
+	private _module: Modules[keyof Modules];
 
-	protected jobFunction: any;
+	private _jobFunction: any;
 
-	protected payload: any;
+	private _payload: any;
 
-	protected context: JobContext;
+	private _context: JobContext;
 
-	protected priority: number;
+	private _priority: number;
 
-	protected longJob?: {
+	private _longJob?: {
 		title: string;
 		progress?: {
 			data: unknown;
@@ -35,19 +35,19 @@ export default class Job {
 		};
 	};
 
-	protected uuid: string;
+	private _uuid: string;
 
-	protected status: JobStatus;
+	private _status: JobStatus;
 
-	protected createdAt: number;
+	private _createdAt: number;
 
-	protected startedAt?: number;
+	private _startedAt?: number;
 
-	protected completedAt?: number;
+	private _completedAt?: number;
 
-	protected logBook: LogBook;
+	private _logBook: LogBook;
 
-	protected jobStatistics: JobStatistics;
+	private _jobStatistics: JobStatistics;
 
 	/**
 	 * Job
@@ -63,21 +63,21 @@ export default class Job {
 		payload: any,
 		options?: Omit<JobOptions, "runDirectly">
 	) {
-		this.name = name;
-		this.priority = 1;
+		this._name = name;
+		this._priority = 1;
 
 		const module = ModuleManager.getPrimaryInstance().getModule(moduleName);
 		if (!module) throw new Error("Module not found.");
-		this.module = module;
+		this._module = module;
 
-		this.jobFunction = this.module.getJob(this.name).method;
+		this._jobFunction = this._module.getJob(this._name).method;
 
-		this.payload = payload;
+		this._payload = payload;
 
-		this.logBook = LogBook.getPrimaryInstance();
+		this._logBook = LogBook.getPrimaryInstance();
 
-		this.jobStatistics = JobStatistics.getPrimaryInstance();
-		this.jobStatistics.updateStats(this.getName(), "added");
+		this._jobStatistics = JobStatistics.getPrimaryInstance();
+		this._jobStatistics.updateStats(this.getName(), "added");
 
 		let contextOptions;
 
@@ -86,18 +86,18 @@ export default class Job {
 
 			if (session || socketId) contextOptions = { session, socketId };
 
-			if (priority) this.priority = priority;
+			if (priority) this._priority = priority;
 
 			if (longJob)
-				this.longJob = {
+				this._longJob = {
 					title: longJob
 				};
 		}
 
-		this.context = new JobContext(this, contextOptions);
+		this._context = new JobContext(this, contextOptions);
 
 		/* eslint-disable no-bitwise, eqeqeq */
-		this.uuid = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(
+		this._uuid = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(
 			/[xy]/g,
 			c => {
 				const r = (Math.random() * 16) | 0;
@@ -105,8 +105,8 @@ export default class Job {
 				return v.toString(16);
 			}
 		);
-		this.status = JobStatus.QUEUED;
-		this.createdAt = Date.now();
+		this._status = JobStatus.QUEUED;
+		this._createdAt = Date.now();
 	}
 
 	/**
@@ -115,7 +115,7 @@ export default class Job {
 	 * @returns module.name
 	 */
 	public getName() {
-		return `${this.module.getName()}.${this.name}`;
+		return `${this._module.getName()}.${this._name}`;
 	}
 
 	/**
@@ -124,7 +124,7 @@ export default class Job {
 	 * @returns priority
 	 */
 	public getPriority() {
-		return this.priority;
+		return this._priority;
 	}
 
 	/**
@@ -133,7 +133,7 @@ export default class Job {
 	 * @returns UUID
 	 */
 	public getUuid() {
-		return this.uuid;
+		return this._uuid;
 	}
 
 	/**
@@ -142,7 +142,7 @@ export default class Job {
 	 * @returns status
 	 */
 	public getStatus() {
-		return this.status;
+		return this._status;
 	}
 
 	/**
@@ -150,8 +150,8 @@ export default class Job {
 	 *
 	 * @param status - Job status
 	 */
-	protected setStatus(status: JobStatus) {
-		this.status = status;
+	private _setStatus(status: JobStatus) {
+		this._status = status;
 	}
 
 	/**
@@ -160,7 +160,7 @@ export default class Job {
 	 * @returns module
 	 */
 	public getModule() {
-		return this.module;
+		return this._module;
 	}
 
 	/**
@@ -169,12 +169,12 @@ export default class Job {
 	 * @returns Promise
 	 */
 	public async execute() {
-		if (this.startedAt) throw new Error("Job has already been executed.");
-		this.setStatus(JobStatus.ACTIVE);
-		this.startedAt = Date.now();
+		if (this._startedAt) throw new Error("Job has already been executed.");
+		this._setStatus(JobStatus.ACTIVE);
+		this._startedAt = Date.now();
 		return (
-			this.jobFunction
-				.apply(this.module, [this.context, this.payload])
+			this._jobFunction
+				.apply(this._module, [this._context, this._payload])
 				// eslint-disable-next-line
 				// @ts-ignore
 				.then(response => {
@@ -182,7 +182,7 @@ export default class Job {
 						message: "Job completed successfully",
 						type: "success"
 					});
-					this.jobStatistics.updateStats(
+					this._jobStatistics.updateStats(
 						this.getName(),
 						"successful"
 					);
@@ -193,19 +193,19 @@ export default class Job {
 						message: `Job failed with error "${err}"`,
 						type: "error"
 					});
-					this.jobStatistics.updateStats(this.getName(), "failed");
+					this._jobStatistics.updateStats(this.getName(), "failed");
 					throw err;
 				})
 				.finally(() => {
-					this.completedAt = Date.now();
-					this.jobStatistics.updateStats(this.getName(), "total");
-					if (this.startedAt)
-						this.jobStatistics.updateStats(
+					this._completedAt = Date.now();
+					this._jobStatistics.updateStats(this.getName(), "total");
+					if (this._startedAt)
+						this._jobStatistics.updateStats(
 							this.getName(),
 							"averageTime",
-							this.completedAt - this.startedAt
+							this._completedAt - this._startedAt
 						);
-					this.setStatus(JobStatus.COMPLETED);
+					this._setStatus(JobStatus.COMPLETED);
 				})
 		);
 	}
@@ -223,7 +223,7 @@ export default class Job {
 		} = {
 			...(typeof log === "string" ? { message: log } : log)
 		};
-		this.logBook.log({
+		this._logBook.log({
 			message,
 			type,
 			category: this.getName(),
@@ -245,10 +245,10 @@ export default class Job {
 			priority: this.getPriority(),
 			name: this.getName(),
 			status: this.getStatus(),
-			moduleStatus: this.module.getStatus(),
-			createdAt: this.createdAt,
-			startedAt: this.startedAt,
-			completedAt: this.completedAt
+			moduleStatus: this._module.getStatus(),
+			createdAt: this._createdAt,
+			startedAt: this._startedAt,
+			completedAt: this._completedAt
 		};
 	}
 }

+ 1 - 1
backend/src/Migration.ts

@@ -7,7 +7,7 @@ export default class Migration {
 		this._mongoConnection = mongoConnection;
 	}
 
-	protected getDb() {
+	protected _getDb() {
 		return this._mongoConnection.db;
 	}
 

+ 8 - 8
backend/src/WebSocket.ts

@@ -2,11 +2,11 @@ import { WebSocket as WSWebSocket } from "ws";
 import LogBook, { Log } from "./LogBook";
 
 export default class WebSocket extends WSWebSocket {
-	protected logBook: LogBook = LogBook.getPrimaryInstance();
+	private _logBook: LogBook = LogBook.getPrimaryInstance();
 
-	protected socketId?: string;
+	private _socketId?: string;
 
-	protected sessionId?: string;
+	private _sessionId?: string;
 
 	public dispatch(name: string, ...args: any[]) {
 		this.send(JSON.stringify([name, ...args]));
@@ -25,7 +25,7 @@ export default class WebSocket extends WSWebSocket {
 		} = {
 			...(typeof log === "string" ? { message: log } : log)
 		};
-		this.logBook.log({
+		this._logBook.log({
 			message,
 			type,
 			category: "modules.websocket.socket",
@@ -34,18 +34,18 @@ export default class WebSocket extends WSWebSocket {
 	}
 
 	public getSocketId() {
-		return this.socketId;
+		return this._socketId;
 	}
 
 	public setSocketId(socketId?: string) {
-		this.socketId = socketId;
+		this._socketId = socketId;
 	}
 
 	public getSessionId() {
-		return this.sessionId;
+		return this._sessionId;
 	}
 
 	public setSessionId(sessionId?: string) {
-		this.sessionId = sessionId;
+		this._sessionId = sessionId;
 	}
 }

+ 6 - 6
backend/src/modules/APIModule.ts

@@ -18,7 +18,7 @@ export default class APIModule extends BaseModule {
 	public constructor() {
 		super("api");
 
-		this.dependentModules = ["data", "events", "websocket"];
+		this._dependentModules = ["data", "events", "websocket"];
 		this._subscriptions = {};
 	}
 
@@ -28,7 +28,7 @@ export default class APIModule extends BaseModule {
 	public override async startup() {
 		await super.startup();
 
-		await super.started();
+		await super._started();
 	}
 
 	/**
@@ -39,7 +39,7 @@ export default class APIModule extends BaseModule {
 
 		await this._removeAllSubscriptions();
 
-		await super.stopped();
+		await super._stopped();
 	}
 
 	/**
@@ -140,7 +140,7 @@ export default class APIModule extends BaseModule {
 
 		socket.on("close", async () => {
 			if (socketId)
-				await this.jobQueue.runJob("api", "unsubscribeAll", {
+				await this._jobQueue.runJob("api", "unsubscribeAll", {
 					socketId
 				});
 		});
@@ -222,7 +222,7 @@ export default class APIModule extends BaseModule {
 		const promises = [];
 		for await (const socketId of this._subscriptions[channel].values()) {
 			promises.push(
-				this.jobQueue.runJob("websocket", "dispatch", {
+				this._jobQueue.runJob("websocket", "dispatch", {
 					socketId,
 					channel,
 					value
@@ -315,7 +315,7 @@ export default class APIModule extends BaseModule {
 					const promises = [];
 					for await (const socketId of socketIds.values()) {
 						promises.push(
-							this.jobQueue.runJob("api", "unsubscribe", {
+							this._jobQueue.runJob("api", "unsubscribe", {
 								socketId,
 								channel
 							})

+ 7 - 7
backend/src/modules/DataModule.ts

@@ -119,9 +119,9 @@ export default class DataModule extends BaseModule {
 	public constructor() {
 		super("data");
 
-		this.dependentModules = ["events"];
+		this._dependentModules = ["events"];
 
-		this.jobConfig = {
+		this._jobConfig = {
 			getModel: false
 		};
 	}
@@ -167,7 +167,7 @@ export default class DataModule extends BaseModule {
 		//				}`
 		//			);
 
-		await super.started();
+		await super._started();
 	}
 
 	/**
@@ -178,7 +178,7 @@ export default class DataModule extends BaseModule {
 		//		if (this._redisClient) await this._redisClient.quit();
 		patchEventEmitter.removeAllListeners();
 		if (this._mongoConnection) await this._mongoConnection.close();
-		await this.stopped();
+		await this._stopped();
 	}
 
 	/**
@@ -313,7 +313,7 @@ export default class DataModule extends BaseModule {
 			.filter(([, event]) => !!event)
 			.forEach(([action, event]) => {
 				patchEventEmitter.on(event, async ({ doc }) => {
-					await this.jobQueue.runJob("events", "publish", {
+					await this._jobQueue.runJob("events", "publish", {
 						channel: `model.${modelName}.${doc._id}.${action}`,
 						value: doc
 					});
@@ -443,7 +443,7 @@ export default class DataModule extends BaseModule {
 			Object.entries(this._models).map(async ([modelName, model]) => {
 				await Promise.all(
 					["findById"].map(async method => {
-						this.jobConfig[`${modelName}.${method}`] = {
+						this._jobConfig[`${modelName}.${method}`] = {
 							method: async (context, payload) =>
 								Object.getPrototypeOf(this)[`_${method}`](
 									context,
@@ -458,7 +458,7 @@ export default class DataModule extends BaseModule {
 
 				await Promise.all(
 					Object.keys(model.schema.statics).map(async name => {
-						this.jobConfig[`${modelName}.${name}`] = {
+						this._jobConfig[`${modelName}.${name}`] = {
 							method: async (...args) => model[name](...args)
 						};
 					})

+ 3 - 3
backend/src/modules/EventsModule.ts

@@ -22,7 +22,7 @@ export default class EventsModule extends BaseModule {
 
 		this._subscriptions = {};
 		this._scheduleCallbacks = {};
-		this.jobApiDefault = false;
+		this._jobApiDefault = false;
 	}
 
 	/**
@@ -34,7 +34,7 @@ export default class EventsModule extends BaseModule {
 		await this._createPubClient();
 		await this._createSubClient();
 
-		await super.started();
+		await super._started();
 	}
 
 	/**
@@ -292,7 +292,7 @@ export default class EventsModule extends BaseModule {
 		this._subscriptions = {};
 		this._scheduleCallbacks = {};
 
-		await this.stopped();
+		await this._stopped();
 	}
 }
 

+ 3 - 3
backend/src/modules/StationModule.ts

@@ -9,7 +9,7 @@ export default class StationModule extends BaseModule {
 	public constructor() {
 		super("stations");
 
-		this.dependentModules = ["data"];
+		this._dependentModules = ["data"];
 	}
 
 	/**
@@ -18,7 +18,7 @@ export default class StationModule extends BaseModule {
 	public override async startup() {
 		await super.startup();
 		this.log("Station Startup");
-		await super.started();
+		await super._started();
 	}
 
 	/**
@@ -26,7 +26,7 @@ export default class StationModule extends BaseModule {
 	 */
 	public override async shutdown() {
 		await super.shutdown();
-		await super.stopped();
+		await super._stopped();
 	}
 
 	/**

+ 7 - 7
backend/src/modules/WebSocketModule.ts

@@ -22,7 +22,7 @@ export default class WebSocketModule extends BaseModule {
 	public constructor() {
 		super("websocket");
 
-		this.jobApiDefault = false;
+		this._jobApiDefault = false;
 	}
 
 	/**
@@ -53,7 +53,7 @@ export default class WebSocketModule extends BaseModule {
 			clearInterval(this._keepAliveInterval)
 		);
 
-		await super.started();
+		await super._started();
 	}
 
 	/**
@@ -87,7 +87,7 @@ export default class WebSocketModule extends BaseModule {
 		socket: WebSocket,
 		request: IncomingMessage
 	) {
-		if (this.jobQueue.getStatus().isPaused) {
+		if (this._jobQueue.getStatus().isPaused) {
 			socket.close();
 			return;
 		}
@@ -126,7 +126,7 @@ export default class WebSocketModule extends BaseModule {
 	 * handleMessage - Handle websocket message
 	 */
 	private async _handleMessage(socket: WebSocket, message: RawData) {
-		if (this.jobQueue.getStatus().isPaused) {
+		if (this._jobQueue.getStatus().isPaused) {
 			socket.close();
 			return;
 		}
@@ -150,13 +150,13 @@ export default class WebSocketModule extends BaseModule {
 					`No callback reference provided for job ${moduleJob}`
 				);
 
-			const module = this.moduleManager.getModule(moduleName);
+			const module = this._moduleManager.getModule(moduleName);
 			if (!module) throw new Error(`Module "${moduleName}" not found`);
 
 			const job = module.getJob(jobName);
 			if (!job.api) throw new Error(`Job "${jobName}" not found.`);
 
-			const res = await this.jobQueue.runJob("api", "runJob", {
+			const res = await this._jobQueue.runJob("api", "runJob", {
 				moduleName,
 				jobName,
 				payload,
@@ -245,7 +245,7 @@ export default class WebSocketModule extends BaseModule {
 		if (this._httpServer) this._httpServer.close();
 		if (this._wsServer) this._wsServer.close();
 
-		await this.stopped();
+		await this._stopped();
 	}
 }
 

+ 1 - 1
backend/src/schemas/migrations/1620330161000-news-markdown.ts

@@ -2,7 +2,7 @@ import Migration from "../../Migration";
 
 export default class Migration1620330161000 extends Migration {
 	async up() {
-		const News = this.getDb().collection("news");
+		const News = this._getDb().collection("news");
 
 		const newsItems = News.find({ documentVersion: 1 }).stream();